PHP sort array: sort, asort, ksort and usort compared, with examples
Which PHP sort function to use, in one table: by value or key, keep keys or not, ascending or descending, or with your own comparison. Plus sorting by a column, by several fields and naturally.
On this page
PHP has twelve sort functions, and the right one depends on three questions: do you sort by value or key, do you need to keep the keys, and is the default order enough or do you need your own comparison? Every one of them sorts the array in place and returns true, so never write $sorted = sort($array);.
Which sort function to use
| Function | Sorts by | Keys | Order |
|---|---|---|---|
sort() |
value | reindexed 0, 1, 2… | ascending |
rsort() |
value | reindexed | descending |
asort() |
value | kept | ascending |
arsort() |
value | kept | descending |
ksort() |
key | kept | ascending |
krsort() |
key | kept | descending |
usort() |
value, your callback | reindexed | yours |
uasort() |
value, your callback | kept | yours |
uksort() |
key, your callback | kept | yours |
natsort() / natcasesort() |
value, “natural” order | kept | ascending |
array_multisort() |
several arrays or columns | string keys kept | per column |
The pattern is easy to remember: a keeps the association between key and value, k sorts by key, r reverses, u takes a user callback.
$prices = ['tea' => 3.5, 'coffee' => 4.2, 'water' => 1.0];
sort($prices); // [1.0, 3.5, 4.2] keys lost
asort($prices); // ['water' => 1.0, 'tea' => 3.5, 'coffee' => 4.2] keys kept
ksort($prices); // ['coffee' => 4.2, 'tea' => 3.5, 'water' => 1.0] by key
arsort($prices); // ['coffee' => 4.2, 'tea' => 3.5, 'water' => 1.0] by value, high first
The most common bug is using sort() on an associative array and losing the keys. If the keys mean something, use asort() or ksort().
Sorting without changing the original
Because the functions work by reference, sort a copy when you need both versions. Arrays are copied on write, so this is cheap until the sort happens:
$sorted = $prices;
asort($sorted);
Passing a function call such as sort(getPrices()) does not work: only a variable can be passed by reference.
Sort flags: numbers, strings and natural order
The basic functions take an optional flag that controls how values are compared:
$files = ['img12.png', 'img10.png', 'IMG2.png', 'img1.png'];
sort($files); // IMG2.png, img1.png, img10.png, img12.png
sort($files, SORT_NATURAL | SORT_FLAG_CASE); // img1.png, IMG2.png, img10.png, img12.png
$ids = ['10', '9', '100'];
sort($ids, SORT_STRING); // '10', '100', '9'
sort($ids, SORT_NUMERIC); // '9', '10', '100'
SORT_REGULAR (the default) compares with PHP’s normal comparison rules, which can give odd results when an array mixes numbers and non-numeric strings. If the data is all one kind, say so with SORT_NUMERIC or SORT_STRING. For language-aware ordering of words with accents, use Collator::sort() from the intl extension.
Sort an array of arrays by a column with usort()
usort() takes a callback that returns a negative number, zero or a positive number. The spaceship operator <=> does exactly that:
$users = [
['name' => 'Ana', 'age' => 34],
['name' => 'Bilal', 'age' => 27],
['name' => 'Chen', 'age' => 34],
];
usort($users, fn (array $a, array $b) => $a['age'] <=> $b['age']); // youngest first
usort($users, fn (array $a, array $b) => $b['age'] <=> $a['age']); // oldest first (swap $a and $b)
usort($users, fn (array $a, array $b) => strcmp($a['name'], $b['name']));
Use uasort() instead if the outer keys (for example user IDs) must survive. For objects, compare properties the same way: fn (User $a, User $b) => $a->createdAt <=> $b->createdAt.
Do not return a boolean such as $a['age'] > $b['age']. It treats “less than” and “equal” the same, and PHP 8 emits a deprecation warning for it.
Sort by several fields
Compare arrays with <=>: PHP compares them element by element, so the second field only decides ties in the first.
// Age descending, then name ascending.
usort($users, fn ($a, $b) => [$b['age'], $a['name']] <=> [$a['age'], $b['name']]);
Stable sorting since PHP 8.0
Since PHP 8.0, every sort is stable: elements that compare as equal keep their original order. In the example above, sorting by age alone leaves Ana before Chen because that is the order they started in. On PHP 7, equal elements could come out in any order, and code that relied on an earlier sort being preserved could shuffle between runs. If you still support PHP 7, add a tie-breaker field to the comparison. Use the PHP version checker to see which version your code needs.
Sorting multidimensional arrays with array_multisort()
array_multisort() sorts one array by the values of another, which suits columnar data:
$ages = array_column($users, 'age');
$names = array_column($users, 'name');
array_multisort($ages, SORT_DESC, $names, SORT_ASC, $users);
It is fast for large datasets, but harder to read than usort() with <=>. Reach for it when profiling says the callback is the bottleneck.
Shuffle, reverse and other non-sorts
array_reverse($array, true)flips the order and returns a new array;truekeeps the keys.shuffle($array)randomises in place and reindexes. For security-sensitive shuffles, useRandom\Randomizer::shuffleArray()(PHP 8.2+).- To get just the smallest or largest value,
min()andmax()are faster than sorting.
Once sorted, array_map() and array_filter() keep the order, so you can sort first and transform after. See array_map and array_filter.