PHP
Sort Multidimensional PHP Array by Custom Key Value
Learn to sort an array of associative arrays in PHP using usort() and a custom comparison function to order by a specific key's value (e.g., age, price).
<?php
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
['name' => 'David', 'age' => 25],
];
// Sort users by 'age' in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // Spaceship operator for comparison
});
print_r($users);
// Sort users by 'name' in descending order
usort($users, function($a, $b) {
return $b['name'] <=> $a['name'];
});
print_r($users);
?>
How it works: When dealing with arrays of arrays (e.g., database results), `usort()` is invaluable for custom sorting. It takes the array and a callback function which defines the comparison logic between two elements. The spaceship operator (`<=>`) simplifies comparison, returning -1, 0, or 1 based on the relative values, making it easy to sort by any specific key in ascending or descending order.