Sort a 2d Array by One of the Columns
Working with multidimensional arrays in PHP often feels like managing a miniature database within your application's memory. You frequently encounter structures where each index represents a row, and the values inside are associative arrays containing column names. The scenario is common: you have a list of items, perhaps fetched from an API or generated dynamically, and you need to order them based on a specific criterion, such as price, date, or priority.
Consider a dataset representing inventory where each item has a name and a price. To reorder these rows by the price column in ascending order without preserving the original numeric keys, you must utilize PHP's native sorting capabilities effectively.
The most direct approach for this specific requirement is the usort() function. Unlike sort(), which reindexes an array sequentially starting from 0 and ignores the internal structure of elements, usort() expects a callback function that defines the sorting logic. This callback receives two parameters: the first element ($a) and the second element ($b). It must return an integer to determine the sort order.
Here is how you can implement this for the TV inventory example:
$data = [
['name' => 'Sony TV', 'price' => 600.00],
['name' => 'LG TV', 'price' => 350.00],
['name' => 'Samsung TV', 'price' => 425.00],
];
usort($data, function ($a, $b) {
if ($a['price'] < $b['price']) {
return -1;
} elseif ($a['price'] == $b['price']) {
return 0;
} else {
return 1;
}
});
print_r($data);
This code produces the desired output, with 'LG TV' appearing first and 'Sony TV' last. The logic explicitly compares the price keys of the two arrays passed to the callback. If $a is less than $b, it returns -1 (ascending); if they are equal, it returns 0; otherwise, it returns 1. This manual comparison ensures that the array is sorted strictly by the specified column.
However, as your data structures evolve, writing out if/elseif/else blocks for every comparison becomes tedious and error-prone. PHP 7 introduced a more concise syntax using the spaceship operator (<=>). This operator returns -1 if $a is less than $b, 0 if they are equal, and 1 if $a is greater. You can collapse the entire comparison logic into a single line:
usort($data, fn ($a, $b) => $a['price'] <=> $b['price']);
Using fn for an anonymous function also reduces character count and visual clutter. This approach handles null values gracefully in many contexts, though you should verify your data integrity to ensure keys like price always exist before comparison to avoid fatal errors.
If you are working within a Laravel project, the ecosystem offers additional abstractions that might simplify this process further. Laravel's Collect facade provides a fluent interface for handling arrays. By wrapping your multidimensional array in collect(), you can chain methods like sortBy() and values(). This pattern is particularly useful when you want to preserve readability while sorting complex datasets:
use Illuminate\Support\Collect;
$sortedData = collect($data)->sortBy('price')->values()->toArray();
The sortBy() method automatically sorts the collection by the specified key, and values() re-indexes the outer array starting from 0, discarding the original keys. This aligns perfectly with the requirement to not preserve the outer array's indices. Note that sortBy performs an ascending sort by default; use sortByDesc('price') for descending order.
While usort is strictly procedural and works in vanilla PHP environments without dependencies, the Laravel collection syntax is just a syntactic sugar over the underlying logic. It doesn't change performance characteristics but significantly improves code clarity. The choice between them depends on your environment constraints and whether you need to interact with native PHP arrays or can leverage the Collection class. Always ensure that the column you are sorting against contains comparable data types; mixing strings and integers in a sort operation without explicit casting will yield unexpected results.