PHP

Sort Associative Array by Multiple Keys (Custom Comparator)

Implement custom sorting for an array of associative arrays in PHP, allowing you to prioritize and sort by multiple keys (e.g., name then age).

<?php
$users = [
    ['name' => 'John', 'age' => 30, 'city' => 'New York'],
    ['name' => 'Alice', 'age' => 25, 'city' => 'London'],
    ['name' => 'Bob', 'age' => 30, 'city' => 'Paris'],
    ['name' => 'Alice', 'age' => 28, 'city' => 'Berlin'],
];

// Sort by 'age' (ascending) then by 'name' (ascending)
usort($users, function($a, $b) {
    if ($a['age'] == $b['age']) {
        return $a['name'] <=> $b['name']; // PHP 7+ spaceship operator
    }
    return $a['age'] <=> $b['age'];
});

/*
$users will be:
[
    ['name' => 'Alice', 'age' => 25, 'city' => 'London'],
    ['name' => 'Alice', 'age' => 28, 'city' => 'Berlin'],
    ['name' => 'Bob', 'age' => 30, 'city' => 'Paris'],
    ['name' => 'John', 'age' => 30, 'city' => 'New York']
]
*/
?>
How it works: The `usort` function sorts an array by values using a user-defined comparison function. The provided anonymous function compares two elements (`$a`, `$b`). It first compares `age`. If ages are equal, it then compares `name`, ensuring a stable sort order based on multiple criteria. The spaceship operator (`<=>`) simplifies comparison for PHP 7+.

Need help integrating this into your project?

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

Hire DigitalCodeLabs