PHP

Sort Multi-dimensional PHP Arrays by a Key

Learn to efficiently sort multi-dimensional PHP arrays based on the value of a specific nested key, enabling ordered data presentation and better readability.

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

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

// To sort by 'name' alphabetically:
// usort($users, function($a, $b) {
//     return strcmp($a['name'], $b['name']);
// });

print_r($users);
?>
How it works: This snippet demonstrates how to sort an array of associative arrays (or objects) by the value of a specific key. The `usort()` function is used with a custom comparison callback. The spaceship operator (`<=>`) is ideal for numerical comparisons, returning -1, 0, or 1. For string comparisons, `strcmp()` is recommended to ensure correct alphabetical ordering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs