PHP 8 reference · 13 entries
PHP Array Sorting Functions
Every PHP array sorting function compared: sort(), rsort(), usort(), asort(), ksort(), natsort() and more, with which ones keep keys.
All sorting functions change the array in place and return true, not the sorted array. They differ in
what they sort by and whether keys survive:
| Function | Sorts by | Order | Keeps keys |
|---|---|---|---|
sort() / rsort() |
value | ascending / descending | no |
asort() / arsort() |
value | ascending / descending | yes |
ksort() / krsort() |
key | ascending / descending | yes |
usort() |
value | your function | no |
uasort() / uksort() |
value / key | your function | yes |
natsort() / natcasesort() |
value | natural | yes |
Since PHP 8.0, sorting is stable: equal elements keep their original order.
| Name | Description | Since |
|---|---|---|
sort() |
Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0. | 4.0 |
rsort() |
Sort an array's values in descending order, in place. Keys are discarded and the result is renumbered from 0. | 4.0 |
usort() |
Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons. | 4.0 |
asort() |
Sort an array by value in ascending order, keeping each key attached to its value. Ideal for name => score maps. | 4.0 |
arsort() |
Sort an array by value in descending order, keeping each key attached to its value. Great for leaderboards. | 4.0 |
uasort() |
Sort an array by value with your own comparison function, keeping keys attached to their values. | 4.0 |
ksort() |
Sort an array by key in ascending order, keeping each value with its key. | 4.0 |
krsort() |
Sort an array by key in descending order, keeping each value with its key. | 4.0 |
uksort() |
Sort an array by key with your own comparison function, keeping values with their keys. | 4.0 |
natsort() |
Sort an array in natural order, so "img2" comes before "img10", keeping keys. Case-sensitive. | 4.0 |
natcasesort() |
Sort an array in natural order while ignoring case, keeping keys. "Item2" comes before "item10". | 4.0 |
shuffle() |
Shuffle an array into a random order, in place. Keys are discarded. Not suitable for security-sensitive randomness. | 4.0 |
array_multisort() |
Sort several arrays at once, or a table by several columns, keeping rows lined up. Changes the arrays in place. | 4.0 |