PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.
The main differences are:
$array['key'] = 'value';
Function name | Sorts by | Maintains key association | Order of sort | Related functions |
---|---|---|---|---|
array_multisort() | value | string keys yes, int keys no | first array or sort options | array_walk() |
asort() | value | yes | ascending | arsort() |
arsort() | value | yes | descending | asort() |
krsort() | key | yes | descending | ksort() |
ksort() | key | yes | ascending | krsort() |
natcasesort() | value | yes | natural, case insensitive | natsort() |
natsort() | value | yes | natural | natcasesort() |
rsort() | value | no | descending | sort() |
shuffle() | value | no | random | array_rand() |
sort() | value | no | ascending | rsort() |
uasort() | value | yes | user defined | uksort() |
uksort() | key | yes | user defined | uasort() |
usort() | value | no | user defined | uasort() |
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.
The following code:
<?php
function usortTest($a, $b) {
var_dump($a);
var_dump($b);
return -1;
}
$test = array('val1');
usort($test, "usortTest");
$test2 = array('val2', 'val3');
usort($test2, "usortTest");
?>
Will output:
string(4) "val3"
string(4) "val2"
The first array doesn't get sent to the function.
Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.
Another way to do a case case-insensitive sort by key would simply be:
<?php
uksort($array, 'strcasecmp');
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.