PHP
Sort PHP Associative Arrays by Key Value with `usort`
Discover how to sort an array of associative arrays or objects in PHP based on the value of a specific key (e.g., 'price' or 'date') using `usort` and a custom comparison function.
<?php
$students = [
['name' => 'Alice', 'score' => 85, 'age' => 20],
['name' => 'Bob', 'score' => 92, 'age' => 22],
['name' => 'Charlie', 'score' => 78, 'age' => 21],
['name' => 'David', 'score' => 92, 'age' => 19]
];
// Sort students by score in descending order, then by age in ascending for ties
usort($students, function($a, $b) {
if ($a['score'] === $b['score']) {
return $a['age'] <=> $b['age']; // Sort by age if scores are equal
}
return $b['score'] <=> $a['score']; // Sort by score descending
});
print_r($students);
/*
Output:
Array
(
[0] => Array
(
[name] => David
[score] => 92
[age] => 19
)
[1] => Array
(
[name] => Bob
[score] => 92
[age] => 22
)
[2] => Array
(
[name] => Alice
[score] => 85
[age] => 20
)
[3] => Array
(
[name] => Charlie
[score] => 78
[age] => 21
)
)
*/
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. This snippet demonstrates how to sort an array of student records. The custom comparison function first sorts by 'score' in descending order. If two students have the same score, it then uses the 'age' key to sort them in ascending order, providing a multi-criteria sorting capability crucial for complex data sets.