PHP
Sort PHP Associative Array by Key Value
Discover how to sort a PHP array containing multiple associative arrays or objects based on the value of a specific key using usort() and a custom comparison function.
<?php
$users = [
['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
['name' => 'Bob', 'age' => 25, 'city' => 'London'],
['name' => 'Charlie', 'age' => 35, 'city' => 'Paris'],
['name' => 'David', 'age' => 25, 'city' => 'Berlin'],
];
// Sort users by 'age' in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
});
echo "Sorted by Age (Ascending):
";
print_r($users);
// Sort users by 'name' in descending order
usort($users, function($a, $b) {
return $b['name'] <=> $a['name']; // Reverse comparison for descending
});
echo "
Sorted by Name (Descending):
";
print_r($users);
?>
How it works: This code snippet illustrates how to sort an array of associative arrays based on a specific key using usort(). The usort() function uses a user-defined comparison function to determine the order of elements. The spaceship operator (<=>) is employed for concise comparison, returning -1, 0, or 1 based on whether the first operand is less than, equal to, or greater than the second.