Sorting Arrays
In PHP, an array is a collection of elements that are stored and accessed using an index or a key. Arrays are a fundamental data structure in PHP, and they are
Introduction to PHP Array Sorting
An array in PHP is a collection of elements stored and accessed by an index (a numeric position) or a key (a label). Sorting means rearranging those elements into a defined order — ascending, descending, by value, by key, or by your own rule.
This page covers PHP's built-in sorting functions, how each one behaves, and — just as importantly — which one to reach for depending on whether you care about keys, values, or a custom order.
How the sort functions differ
Two questions decide which function you need:
- Sort by value or by key? Plain lists (indexed arrays) sort by value; associative arrays can sort by either.
- Keep the key→value association?
sort()/rsort()discard the original keys and re-index from0. Thea*andk*family preserves the association.
| Function | Sorts by | Order | Keeps keys? |
|---|---|---|---|
sort() | value | ascending | no (re-indexed) |
rsort() | value | descending | no (re-indexed) |
asort() | value | ascending | yes |
arsort() | value | descending | yes |
ksort() | key | ascending | yes |
krsort() | key | descending | yes |
usort() | value (custom) | your rule | no (re-indexed) |
uasort() | value (custom) | your rule | yes |
uksort() | key (custom) | your rule | yes |
Every one of these sorts the array in place (it mutates the variable you pass) and returns true on success rather than a new array — a common point of confusion for newcomers.
Sorting Arrays in Ascending Order
The sort() function sorts an array in ascending order: strings alphabetically, numbers numerically. It modifies the original array in place and re-indexes it from 0, so any original keys are lost. Avoid mixing data types in one array, as comparisons between, say, strings and numbers can produce surprising results.
$fruits = ['lemon', 'orange', 'banana', 'apple'];
sort($fruits);
print_r($fruits);
// Output: Array ( [0] => apple [1] => banana [2] => lemon [3] => orange )Sorting Arrays in Descending Order
The rsort() function is the reverse of sort() — it orders elements from highest to lowest. Like sort(), it works in place and re-indexes the array.
$numbers = [5, 2, 9, 1, 7];
rsort($numbers);
print_r($numbers);
// Output: Array ( [0] => 9 [1] => 7 [2] => 5 [3] => 2 [4] => 1 )Sorting Associative Arrays by Value
When the keys carry meaning (names, IDs, labels), use the a* functions so the key→value pairs stay together. The asort() function sorts by value in ascending order; arsort() does the same in descending order.
$ages = ['Peter' => 35, 'John' => 28, 'Mary' => 32];
asort($ages);
print_r($ages);
// Output: Array ( [John] => 28 [Mary] => 32 [Peter] => 35 )Notice that each name stays attached to its age — that is the difference from sort(), which would throw the names away.
Sorting Associative Arrays by Key
The ksort() function sorts by key in ascending order while keeping each key bound to its value; krsort() sorts by key in descending order.
$colors = ['red' => '#FF0000', 'blue' => '#0000FF', 'green' => '#008000'];
ksort($colors);
print_r($colors);
// Output: Array ( [blue] => #0000FF [green] => #008000 [red] => #FF0000 )Natural-Order Sorting
A regular string sort compares character by character, so 'img10' sorts before 'img2' (because '1' < '2'). The natsort() function uses a "natural order" algorithm that compares embedded numbers as numbers — the way a human would order filenames. It preserves keys.
$files = ['img12.png', 'img10.png', 'img2.png', 'img1.png'];
natsort($files);
print_r($files);
// Output: Array ( [3] => img1.png [2] => img2.png [1] => img10.png [0] => img12.png )Use natcasesort() for the same behavior, ignoring upper/lower case.
Custom Sorting with usort()
When the built-in orders are not enough — sorting objects, multidimensional arrays, or by a derived value — usort() lets you supply your own comparison function. The callback receives two elements and must return a negative number, 0, or a positive number depending on whether the first should come before, equal to, or after the second.
$people = [
['name' => 'Mary', 'age' => 32],
['name' => 'Peter', 'age' => 35],
['name' => 'John', 'age' => 28],
];
usort($people, function ($a, $b) {
return $a['age'] <=> $b['age']; // spaceship operator: ascending by age
});
foreach ($people as $person) {
echo $person['name'] . ': ' . $person['age'] . "\n";
}
// Output:
// John: 28
// Mary: 32
// Peter: 35The <=> "spaceship" operator returns exactly the -1 / 0 / 1 that the callback needs, which makes it the idiomatic choice here. If you need to keep keys, use uasort(); to sort by a custom key rule, use uksort().
Choosing the Right Function
- Plain list, don't care about keys →
sort()/rsort(). - Associative array, sort by value, keep keys →
asort()/arsort(). - Associative array, sort by key →
ksort()/krsort(). - Filenames or version-like strings →
natsort()/natcasesort(). - Objects, nested arrays, or any custom rule →
usort()/uasort()/uksort().
If you only need to flip the existing order without re-sorting, array_reverse() is cheaper than a full sort. To sort multiple arrays together or by multiple columns, see array_multisort().
Conclusion
PHP ships a complete toolkit for ordering arrays, and the right choice comes down to two questions: are you sorting by value or by key, and do you need to keep the keys attached? sort() and rsort() handle simple lists, the a*/k* family handles associative data, natsort() handles human-friendly ordering, and the u* family handles anything custom. Remember that all of these sort in place and return a boolean — not a new array.