PHP
Custom Sort Multidimensional PHP Arrays with `usort`
Learn to sort arrays of arrays or objects in PHP using `usort` and a custom comparison function, enabling flexible ordering based on specific keys or logic.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['name' => 'Keyboard', 'price' => 75, 'category' => 'Accessories'],
['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics'],
['name' => 'Mouse', 'price' => 25, 'category' => 'Accessories'],
];
// Sort products by price in ascending order
usort($products, function($a, $b) {
return $a['price'] <=> $b['price']; // PHP 7+ spaceship operator
// For PHP < 7.0:
// if ($a['price'] == $b['price']) return 0;
// return ($a['price'] < $b['price']) ? -1 : 1;
});
echo "Sorted by price (ascending):
";
print_r($products);
// Sort products by category (ascending) then by price (descending)
usort($products, function($a, $b) {
$categoryComparison = $a['category'] <=> $b['category'];
if ($categoryComparison === 0) {
// If categories are the same, sort by price descending
return $b['price'] <=> $a['price'];
}
return $categoryComparison;
});
echo "
Sorted by category (asc) then price (desc):
";
print_r($products);
?>
How it works: The `usort` function allows sorting an array by values using a user-defined comparison function. This is particularly useful for sorting multidimensional arrays or arrays of objects based on one or more specific keys or complex logic. The callback function receives two elements from the array and must return an integer less than, equal to, or greater than zero if the first argument is considered respectively less than, equal to, or greater than the second. PHP 7+ provides the convenient spaceship operator (`<=>`) for comparisons.