PHP

Sort an Array of Associative Arrays by Key

Discover how to sort a list of associative arrays in PHP based on the values of a specified key, using the versatile `usort()` function for custom sorting.

<?php

$articles = [
    ['id' => 101, 'title' => 'PHP Basics', 'views' => 1500],
    ['id' => 102, 'title' => 'Advanced SQL', 'views' => 2100],
    ['id' => 103, 'title' => 'JavaScript ES6', 'views' => 900],
    ['id' => 104, 'title' => 'Modern CSS', 'views' => 2100]
];

// Sort articles by 'views' in descending order
usort($articles, function($a, $b) {
    return $b['views'] <=> $a['views']; // Spaceship operator for comparison
});

print_r($articles);

// Output:
// Array
// (
//     [0] => Array
//         (
//             [id] => 102
//             [title] => Advanced SQL
//             [views] => 2100
//         )
//     [1] => Array
//         (
//             [id] => 104
//             [title] => Modern CSS
//             [views] => 2100
//         )
//     [2] => Array
//         (
//             [id] => 101
//             [title] => PHP Basics
//             [views] => 1500
//         )
//     [3] => Array
//         (
//             [id] => 103
//             [title] => JavaScript ES6
//             [views] => 900
//         )
// )
How it works: `usort()` allows sorting an array by a user-defined comparison function. This is particularly useful for arrays of associative arrays, where you need to sort based on a specific key's value (e.g., sorting users by age, products by price). The callback function should return -1, 0, or 1 based on the comparison of its two arguments, indicating which element comes first.

Need help integrating this into your project?

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

Hire DigitalCodeLabs