How to Sort Arrays in PHP
Sorting arrays is one of the most common tasks in PHP development. Whether you’re dealing with simple numeric lists, associative arrays, or complex multidimensional structures, PHP offers a rich set of functions to sort data efficiently. This guide walks you through the core sorting functions, custom sorting techniques, and performance considerations to help you write clean, maintainable code.
Table of Contents
- Basic Sorting Functions
- Sorting Associative Arrays
- Custom Sorting with Callbacks
- Sorting Multidimensional Arrays
- Performance Tips & Common Pitfalls
Basic Sorting Functions
For simple indexed arrays, PHP provides three primary functions that differ in how they treat keys and order:
sort() – Ascending Value Sort
$numbers = [5, 2, 9, 1];
sort($numbers); // $numbers becomes [1, 2, 5, 9]
sort() reindexes the array, discarding original keys. Use it when the numeric index does not matter.
rsort() – Descending Value Sort
$numbers = [5, 2, 9, 1];
rsort($numbers); // $numbers becomes [9, 5, 2, 1]
shuffle() – Random Order
$cards = range(1, 52);
shuffle($cards); // Randomizes the order of $cards
Sorting Associative Arrays
When you need to preserve keys, PHP offers asort(), arsort(), ksort(), and krsort().
asort() – Ascending Value Sort (maintains keys)
$scores = ['Alice' => 85, 'Bob' => 92, 'Carol' => 78];
asort($scores);
// Result: ['Carol' => 78, 'Alice' => 85, 'Bob' => 92]
arsort() – Descending Value Sort (maintains keys)
arsort($scores);
// Result: ['Bob' => 92, 'Alice' => 85, 'Carol' => 78]
ksort() – Ascending Key Sort
ksort($scores);
// Result: ['Alice' => 85, 'Bob' => 92, 'Carol' => 78]
krsort() – Descending Key Sort
krsort($scores);
// Result: ['Carol' => 78, 'Bob' => 92, 'Alice' => 85]
Custom Sorting with Callbacks
For more complex criteria, PHP’s usort(), uasort(), and uksort() let you define a comparison function.
usort() – Sort by Value with a User‑Defined Callback
$people = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Carol', 'age' => 35],
];
usort($people, function($a, $b) {
return $a['age'] <=> $b['age']; // Spaceship operator (PHP 7+)
});
// $people is now ordered by age ascending
uasort() – Preserve Keys While Using a Callback
$items = [
'a' => 3,
'b' => 1,
'c' => 2,
];
uasort($items, function($x, $y) {
return $x <=> $y;
});
// Keys remain ['b', 'c', 'a'] after sorting by value
uksort() – Sort by Keys Using a Callback
uksort($items, function($k1, $k2) {
return strcmp($k2, $k1); // Reverse alphabetical order
});
Sorting Multidimensional Arrays
When dealing with arrays of arrays (e.g., database result sets), array_multisort() or usort() with a custom comparator are the go‑to solutions.
array_multisort() – Sort by One or More Columns
3, 'price' => 9.99],
['id' => 1, 'price' => 5.50],
['id' => 2, 'price' => 7.25],
];
$price = array_column($data, 'price');
$id = array_column($data, 'id');
array_multisort($price, SORT_ASC, $id, SORT_DESC, $data);
// $data is now sorted by price ASC, then id DESC
usort() for Complex Logic
'Widget', 'rating' => 4.5, 'sales' => 150],
['name' => 'Gadget', 'rating' => 4.7, 'sales' => 120],
['name' => 'Doohickey', 'rating' => 4.5, 'sales' => 200],
];
usort($products, function($a, $b) {
// Primary: rating DESC, Secondary: sales DESC
$cmp = $b['rating'] <=> $a['rating'];
if ($cmp === 0) {
$cmp = $b['sales'] <=> $a['sales'];
}
return $cmp;
});
Performance Tips & Common Pitfalls
- Avoid unnecessary copying: Functions like
sort()modify the array in place. Passing a copy (e.g.,$sorted = $array;thensort($sorted);) doubles memory usage. - Use the most specific function: If you only need to sort values,
sort()is faster thanasort()because it doesn’t preserve keys. - Beware of type juggling: By default, PHP compares values as strings. Use the
SORT_NUMERICflag for numeric sorting:sort($arr, SORT_NUMERIC); - Leverage built‑in functions:
array_multisort()is implemented in C and is typically faster than a PHP‑levelusort()loop for large datasets. - Profile with microtime: When optimizing, wrap the sort call in
microtime(true)to measure execution time and compare alternatives.
Conclusion
PHP provides a versatile toolbox for sorting arrays, from simple one‑liner functions to fully custom callbacks. By choosing the right function for the job—sort() for indexed lists, asort() for associative values, or usort() for complex logic—you can keep your code readable and performant. Remember to consider key preservation, data types, and memory usage when selecting a sorting strategy.