← Back to all snippets
PHP

Sorting Multidimensional PHP Arrays by a Column

Master custom sorting of PHP arrays containing associative arrays or objects based on a particular column or property using `usort` and a comparison function for precise ordering.

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

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

echo json_encode($users, JSON_PRETTY_PRINT);
/*
Expected output:
[
    {
        "name": "Bob",
        "age": 25
    },
    {
        "name": "David",
        "age": 25
    },
    {
        "name": "Alice",
        "age": 30
    },
    {
        "name": "Charlie",
        "age": 35
    }
]
*/
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. This snippet demonstrates sorting an array of associative arrays (users) first by their 'age' in ascending order, and then by 'name' for users with the same age. The comparison function returns -1 if `a` should come before `b`, 1 if `b` should come before `a`, and 0 if they are equal. PHP 7's spaceship operator (`<=>`) simplifies this comparison.

Need help integrating this into your project?

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

Hire DigitalCodeLabs