PHP

Custom Sort an Array of Associative Arrays

Learn to sort complex arrays of associative arrays in PHP by a specific key or custom logic using the versatile `usort()` function and a comparison callback.

<?php
$users = [
    ['id' => 3, 'name' => 'Charlie', 'age' => 30],
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 35],
];

// Sort by 'age' in ascending order
usort($users, function($a, $b) {
    return $a['age'] <=> $b['age']; // Spaceship operator for comparison
});

echo "Sorted by age (ascending):
";
echo json_encode($users, JSON_PRETTY_PRINT);

// Sort by 'name' in descending order
usort($users, function($a, $b) {
    return strcmp($b['name'], $a['name']); // Compare strings in reverse
});

echo "
Sorted by name (descending):
";
echo json_encode($users, JSON_PRETTY_PRINT);

// Output for age:
// [
//     { "id": 1, "name": "Alice", "age": 25 },
//     { "id": 3, "name": "Charlie", "age": 30 },
//     { "id": 2, "name": "Bob", "age": 35 }
// ]
// Output for name:
// [
//     { "id": 3, "name": "Charlie", "age": 30 },
//     { "id": 2, "name": "Bob", "age": 35 },
//     { "id": 1, "name": "Alice", "age": 25 }
// ]
?>
How it works: `usort()` sorts an array by values using a user-defined comparison function. The callback function takes two arguments (`$a` and `$b`) representing elements to compare. It should return an integer less than, equal to, or greater than zero if the first argument is considered respectively less than, equal to, or greater than the second. The spaceship operator (`<=>`) provides a concise way to do this for numerical comparisons.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs