PHP
Sort an Array of Associative Arrays by a Key
Master sorting complex data structures in PHP by a specific key, either in ascending or descending order, using the `usort()` function with a custom comparison callback.
<?php
$users = [
['id' => 103, 'name' => 'Charlie', 'age' => 30],
['id' => 101, 'name' => 'Alice', 'age' => 25],
['id' => 104, 'name' => 'David', 'age' => 35],
['id' => 102, 'name' => 'Bob', 'age' => 28]
];
// Sort by 'age' in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // Spaceship operator for comparison
});
print_r($users);
echo "
";
// Sort by 'name' in descending order
usort($users, function($a, $b) {
return $b['name'] <=> $a['name']; // Reverse comparison for descending
});
print_r($users);
/* Output:
Array
(
[0] => Array
(
[id] => 101
[name] => Alice
[age] => 25
)
[1] => Array
(
[id] => 102
[name] => Bob
[age] => 28
)
[2] => Array
(
[id] => 103
[name] => Charlie
[age] => 30
)
[3] => Array
(
[id] => 104
[name] => David
[age] => 35
)
)
Array
(
[0] => Array
(
[id] => 104
[name] => David
[age] => 35
)
[1] => Array
(
[id] => 103
[name] => Charlie
[age] => 30
)
[2] => Array
(
[id] => 102
[name] => Bob
[age] => 28
)
[3] => Array
(
[id] => 101
[name] => Alice
[age] => 25
)
)
*/
How it works: When dealing with an array of complex data structures (like associative arrays or objects), `usort()` provides the flexibility to sort based on custom logic. It takes the array by reference and a callback function. The callback compares two elements (`$a`, `$b`) from the array and must return an integer less than, equal to, or greater than zero if `$a` is considered to be respectively less than, equal to, or greater than `$b`. PHP 7 introduced the spaceship operator (`<=>`), which simplifies this comparison, returning -1, 0, or 1 directly, making sorting by specific keys much cleaner.