PHP
Custom Sorting an Associative Array by Key
Master custom sorting of PHP associative arrays or arrays of objects using `usort` with a comparison function, enabling flexible ordering based on any key or property.
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 5],
['name' => 'Mouse', 'price' => 25, 'stock' => 50],
['name' => 'Keyboard', 'price' => 75, 'stock' => 20],
];
// Sort by 'price' in ascending order
usort($products, function($a, $b) {
return $a['price'] <=> $b['price']; // Spaceship operator for comparison
});
// Sort by 'stock' in descending order
// usort($products, function($a, $b) {
// return $b['stock'] <=> $a['stock'];
// });
print_r($products);
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. The provided anonymous function takes two array elements (`$a` and `$b`) and returns -1, 0, or 1 based on their comparison, leveraging PHP 7's spaceship operator (`<=>`) for concise ordering. This allows for highly flexible sorting criteria.