How can I sort arrays and data in PHP?
When you need to order a collection of items in PHP, the instinct might be to write a custom comparison function or reach for a third-party library. However, PHP provides a robust set of built-in functions that handle everything from simple lists to complex object graphs. Before reinventing the wheel, it is worth understanding the standard approach versus the SPL (Standard PHP Library) alternatives and when stability matters.
The Standard Approach: usort, uasort, and uksort
For most practical scenarios, you will rely on the three primary sorting functions: sort(), asort(), and usort() for value-based sorting, alongside their associative counterparts. If you are dealing with a one-dimensional array of integers or strings, sort() is sufficient as it reindexes the array numerically.
The real power lies in usort(). This function accepts your array and a callback that defines the sort order. Inside this callback, you receive two values, $a and $b, and must return an integer:
- A negative value if
$ais smaller than$b. - Zero if they are equal.
- A positive value if
$ais larger than$b.
This pattern extends to multidimensional arrays and arrays of objects. Suppose you have a list of users with name and age properties. You can sort them by age using a closure:
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 30],
];
usort($users, function ($a, $b) {
if ($a['age'] == $b['age']) {
return 0;
}
return $a['age'] < $b['age'] ? -1 : 1;
});
A common pitfall here is forgetting to handle the equality case or returning inconsistent types. While PHP is loosely typed, strict comparison logic ensures predictable results. If you need to sort one array based on the values of another parallel array, usort is still applicable; you simply compare the values from the second array inside the callback.
Stability: Preserving Original Order
One critical distinction in sorting algorithms is stability. An unstable sort (like the default implementation of sort()) may reorder elements with equal keys arbitrarily. If your application relies on insertion order for items that share the same sort key, you need a stable sort.
PHP offers uasort() and usort() which are generally considered stable in modern PHP versions, but relying on this behavior can be risky if you upgrade environments. For guaranteed stability across all contexts, use array_multisort() or explicitly leverage the SPL, as discussed next. If you are sorting objects where properties might be equal, a stable sort ensures that the original sequence is preserved for those ties, which is often vital for pagination or caching strategies.
Sorting with the Standard PHP Library (SPL)
For more academic or performance-critical cases, the SPL provides ArrayIterator and SplQueue. You can attach an ArrayIterator to any array and use usort() on it, or utilize the SplSorter class which wraps these iterators. This approach is particularly useful when you are streaming data or working with large datasets where you don't want to reindex the entire array structure unnecessarily.
However, for 95% of web applications, the built-in functions in section 1 above are the pragmatic choice. They are optimized, require no extra memory overhead for iterator wrappers, and integrate seamlessly with Laravel's collection helpers if you are working within that framework.
Complex Arrays and Objects
Sorting complex arraysâthose containing nested structures or mixed typesâis fundamentally the same as sorting simple ones; the complexity lies in your comparison logic. When sorting objects, you might compare specific properties or use magic methods like __invoke to define custom behavior, but usort remains the entry point.
If you are building a Laravel application, remember that Collections provide chainable methods like sortBy() which abstract the underlying uasort mechanism. While convenient, understanding the raw function signatures ensures you can debug sorting issues when dealing with raw arrays outside of Eloquent models.