PHP

Sort Array of Associative Arrays by Custom Key

Learn to sort a PHP array of associative arrays by a specific key, in ascending or descending order, using `usort` and a custom comparison function for flexible data organization.

$students = [
    ['name' => 'John', 'grade' => 85],
    ['name' => 'Alice', 'grade' => 92],
    ['name' => 'Bob', 'grade' => 78],
    ['name' => 'Charlie', 'grade' => 92],
];

// Sort by grade in descending order, then by name in ascending for ties
usort($students, function($a, $b) {
    if ($a['grade'] == $b['grade']) {
        return $a['name'] <=> $b['name']; // PHP 7+ spaceship operator for string comparison
    }
    return $b['grade'] <=> $a['grade']; // Sort grades descending
});

/*
Output:
Array
(
    [0] => Array
        (
            [name] => Alice
            [grade] => 92
        )

    [1] => Array
        (
            [name] => Charlie
            [grade] => 92
        )

    [2] => Array
        (
            [name] => John
            [grade] => 85
        )

    [3] => Array
        (
            [name] => Bob
            [grade] => 78
        )

)
*/
print_r($students);
How it works: The `usort()` function allows sorting an array by a user-defined comparison function. This snippet demonstrates sorting an array of students first by their 'grade' in descending order, and then by 'name' in ascending order for students with the same grade, providing precise control over complex sorting requirements for arrays of associative arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs