Sort array by value alphabetically php

前端 未结 4 1951
我在风中等你
我在风中等你 2020-12-04 01:39

As the title suggests i want to sort an array by value alphabetically in php.

$arr = array(
    \'k\' => \'pig\',
    \'e\' => \'dog\'
)
相关标签:
4条回答
  • 2020-12-04 01:51
    • If you just want to sort the array values and don't care for the keys, use sort(). This will give a new array with numeric keys starting from 0.
    • If you want to keep the key-value associations, use asort().

    See also the comparison table of sorting functions in PHP.

    0 讨论(0)
  • 2020-12-04 02:01

    You want the php function "asort":

    http://php.net/manual/en/function.asort.php

    it sorts the array, maintaining the index associations.

    Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():

    http://php.net/manual/en/function.sort.php

    0 讨论(0)
  • 2020-12-04 02:12

    Note that sort() operates on the array in place, so you only need to call

    sort($a);
    doSomething($a);
    

    This will not work;

    $a = sort($a);
    doSomething($a);
    
    0 讨论(0)
  • 2020-12-04 02:13

    asort() - Maintains key association: yes.

    sort() - Maintains key association: no.

    Source: http://php.net/manual/en/array.sorting.php

    0 讨论(0)
提交回复
热议问题