← Back to all snippets
PHP

Sort Multi-dimensional Array by Specific Key

Learn how to efficiently sort a multi-dimensional PHP array or an array of objects based on the value of a specific key within each nested element.

$data = [
    ['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
    ['name' => 'Bob', 'age' => 25, 'city' => 'Los Angeles'],
    ['name' => 'Charlie', 'age' => 35, 'city' => 'Chicago'],
    ['name' => 'David', 'age' => 25, 'city' => 'Houston'],
];

// Sort by 'age' in ascending order
usort($data, function($a, $b) {
    return $a['age'] <=> $b['age'];
});

// To sort by 'name' in descending order
// usort($data, function($a, $b) {
//     return $b['name'] <=> $a['name'];
// });

print_r($data);
How it works: This snippet demonstrates how to sort an array of arrays (or objects) by a specific key. The `usort()` function sorts an array by values using a user-defined comparison function. The comparison function takes two elements, `$a` and `$b`, and 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. The spaceship operator (`<=>`) simplifies this comparison for numeric or string values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs