PHP

Custom Sort an Array of Associative Arrays in PHP

Discover how to sort complex PHP arrays of associative arrays or objects using `usort()` with a custom comparison function for flexible, multi-criteria ordering.

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

// Sort users by age ascending, then by name ascending for ties
usort($users, function($a, $b) {
    if ($a['age'] == $b['age']) {
        return strcmp($a['name'], $b['name']);
    }
    return $a['age'] - $b['age'];
});

echo "<pre>";
print_r($users);
echo "</pre>";

/*
Output will be:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Bob
            [age] => 25
        )

    [1] => Array
        (
            [id] => 4
            [name] => David
            [age] => 25
        )

    [2] => Array
        (
            [id] => 3
            [name] => Alice
            [age] => 30
        )

    [3] => Array
        (
            [id] => 2
            [name] => Charlie
            [age] => 35
        )

)
*/
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. This function receives two elements (`$a` and `$b`) from the array and must 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. This example sorts by 'age' and then by 'name' for users of the same age, demonstrating powerful custom sorting logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs