PHP

Sorting Multi-Dimensional PHP Arrays by a Specific Key

Learn to effectively sort an array of associative arrays (like database rows) based on the value of a specific key, in ascending or descending order.

<?php
$people = [
    ['name' => 'Charlie', 'age' => 35, 'city' => 'New York'],
    ['name' => 'Alice', 'age' => 30, 'city' => 'London'],
    ['name' => 'Bob', 'age' => 25, 'city' => 'Paris']
];

// Sort by 'age' in ascending order
usort($people, function($a, $b) {
    return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
    // For PHP < 7.0: return $a['age'] - $b['age'];
});
echo "Sorted by age (ascending):
";
print_r($people);

// Sort by 'name' in descending order
usort($people, function($a, $b) {
    return $b['name'] <=> $a['name'];
    // For PHP < 7.0: return strcmp($b['name'], $a['name']);
});
echo "
Sorted by name (descending):
";
print_r($people);

// Output:
// Sorted by age (ascending):
// Array
// (
//     [0] => Array
//         (
//             [name] => Bob
//             [age] => 25
//             [city] => Paris
//         )
//
//     [1] => Array
//         (
//             [name] => Alice
//             [age] => 30
//             [city] => London
//         )
//
//     [2] => Array
//         (
//             [name] => Charlie
//             [age] => 35
//             [city] => New York
//         )
//
// )
//
// Sorted by name (descending):
// Array
// (
//     [0] => Array
//         (
//             [name] => Charlie
//             [age] => 35
//             [city] => New York
//         )
//
//     [1] => Array
//         (
//             [name] => Bob
//             [age] => 25
//             [city] => Paris
//         )
//
//     [2] => Array
//         (
//             [name] => Alice
//             [age] => 30
//             [city] => London
//         )
//
// )
?>
How it works: `usort()` allows sorting an array by a user-defined comparison function. This is crucial for arrays of objects or associative arrays where you need to sort based on a specific property or key. The callback function receives two elements (`$a` and `$b`) and should return `0` if they are equal, `-1` if `$a` should come before `$b`, or `1` if `$b` should come before `$a`. PHP 7's spaceship operator (`<=>`) simplifies numerical and string comparisons significantly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs