PHP
Sort Associative Arrays by Custom Criteria
Learn how to sort complex PHP associative arrays using `usort()` with a custom comparison function, enabling flexible ordering based on any key or logic.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 50],
['name' => 'Mouse', 'price' => 25, 'stock' => 200],
['name' => 'Keyboard', 'price' => 75, 'stock' => 120],
['name' => 'Monitor', 'price' => 300, 'stock' => 30],
];
// Sort products by price in ascending order
usort($products, function($a, $b) {
return $a['price'] <=> $b['price']; // Spaceship operator for comparison
});
echo "Sorted by Price (Ascending):
";
echo json_encode($products, JSON_PRETTY_PRINT) . "
";
// Sort products by stock in descending order
usort($products, function($a, $b) {
return $b['stock'] <=> $a['stock']; // Reverse order for descending
});
echo "Sorted by Stock (Descending):
";
echo json_encode($products, JSON_PRETTY_PRINT) . "
";
?>
How it works: The `usort()` function sorts an array by its values using a user-defined comparison function. This is particularly useful for associative arrays or arrays of objects where you need to sort based on a specific property or a custom logic. The callback function receives two elements (`$a`, `$b`) and should return `0` if they are equal, `1` if `$a` is greater than `$b`, and `-1` if `$a` is less than `$b`. PHP 7's spaceship operator (`<=>`) simplifies this comparison.