Sort an array of associative arrays by column value
Sorting a multidimensional array in PHP often trips up developers who are used to built-in functions that handle simple indexed lists. When your data structure consists of associative arraysâwhere each sub-array represents an entity like a product with keys for type and priceâyou need a different approach than a standard sort(). The goal here is to reorder the $inventory list so that items are arranged by their numeric value in a specific column, such as price.
The most robust way to achieve this in modern PHP is using usort() combined with an anonymous function. This method relies on the comparison logic you define rather than relying on arbitrary sorting algorithms. You pass the array and a callback to usort(), which expects your function to return specific values to determine the order: -1 if the first element should come before the second, 1 if it should come after, and 0 if they are equal.
Here is how you implement this for the $inventory example provided:
$inventory = array(
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
array("type" => "pork", "price" => 5.43),
);
usort($inventory, function ($a, $b) {
// Compare the 'price' column of both arrays
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
});
// Result: Sorted from lowest price to highest
print_r($inventory);
In this implementation, the callback extracts the price key from both arguments. The comparison operators (< and ==) dictate the sort order. If you need descending order (highest price first), simply invert the logic in the return statement or negate the final result. For instance, changing ($a['price'] < $b['price']) ? -1 : 1 to ($a['price'] > $b['price']) ? -1 : 1 will reverse the sequence.
While PHP 8 introduced named arguments and stringable types that simplify many callbacks, this specific pattern remains highly relevant for legacy codebases or environments where strict typing is enforced on function signatures. The usort() approach is also memory efficient because it sorts in place without creating a new array structure first.
Handling Edge Cases and Performance
One common pitfall when sorting associative arrays by a string key, like the type column in this example, is assuming every element possesses that key. If one item is missing the price field, accessing $a['price'] will return null. Comparing null to a float might yield unexpected results depending on your PHP version and strict settings. It is often safer to use the null coalescing operator or explicit checks before comparing values to avoid runtime errors or incorrect sorting orders.
Performance-wise, usort() runs in O(n log n) time complexity, which is standard for comparison-based sorting algorithms. For very large datasets where performance is critical, consider whether a database query with an ORDER BY clause might be more efficient than loading the data into memory and sorting it in PHP. However, for typical application-level inventory lists or configuration arrays, this native function offers sufficient speed without introducing external dependencies.
If you are working within the Laravel ecosystem, remember that the collection facade wraps these native functions with fluent syntax. You can achieve the same result using sortBy on a Collection object, which handles the underlying sorting logic while providing a more readable chain of commands. For raw arrays, however, sticking to usort() ensures maximum compatibility across different PHP versions and avoids the overhead of converting the array to a collection just to sort it back into an array later.
