PHP

Sort Associative Arrays by Custom Criteria with `usort`

Learn to sort PHP associative arrays based on a custom comparison function, useful for ordering complex data structures by specific keys or combinations of keys.

<?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']
];

usort($users, function($a, $b) {
    // Primary sort by age (ascending)
    if ($a['age'] == $b['age']) {
        // Secondary sort by name if ages are equal (alphabetical)
        return strcmp($a['name'], $b['name']);
    }
    return $a['age'] - $b['age'];
});

print_r($users);
/*
Expected Output:
Array
(
    [0] => Array
        (
            [name] => Bob
            [age] => 25
            [city] => London
        )

    [1] => Array
        (
            [name] => David
            [age] => 25
            [city] => Berlin
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 30
            [city] => New York
        )

    [3] => Array
        (
            [name] => Charlie
            [age] => 35
            [city] => Paris
        )

)
*/
How it works: `usort()` allows you to sort an array by values using a user-defined comparison function. This is particularly powerful for associative arrays where you need to sort based on a specific key's value, or even multiple keys. The comparison function should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Here, it sorts users first by age, then by name for those with the same age.

Need help integrating this into your project?

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

Hire DigitalCodeLabs