PHP
Custom Sort Array of Associative Arrays
Master custom sorting of complex PHP arrays. Learn to sort an array of associative arrays based on specific key values using `usort()` for precise ordering.
<?php
$users = [
['name' => 'Bob', 'age' => 30, 'score' => 85],
['name' => 'Alice', 'age' => 25, 'score' => 92],
['name' => 'Charlie', 'age' => 35, 'score' => 85],
];
// Sort by age in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
});
echo "Sorted by age:
";
print_r($users);
// Sort by score in descending order, then by name in ascending order for ties
usort($users, function($a, $b) {
$scoreComparison = $b['score'] <=> $a['score']; // Descending score
if ($scoreComparison === 0) {
return $a['name'] <=> $b['name']; // Ascending name for ties
}
return $scoreComparison;
});
echo "
Sorted by score (desc) then name (asc):
";
print_r($users);
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. The callback function receives two elements (`$a`, `$b`) and should return an integer less than, equal to, or greater than zero if `$a` is considered respectively less than, equal to, or greater than `$b`. The spaceship operator (`<=>`) simplifies comparisons in PHP 7+. This snippet shows sorting by a single key and then by multiple criteria for more complex ordering.