PHP

Sorting an Array of Associative Arrays by Key

Master custom sorting of complex arrays in PHP by using `usort` or `uasort` with a callback, allowing you to order data based on any specific key or criteria.

<?php
$articles = [
    ['title' => 'PHP Arrays Explained', 'views' => 1200, 'published_date' => '2023-01-15'],
    ['title' => 'Mastering Laravel', 'views' => 3500, 'published_date' => '2022-11-01'],
    ['title' => 'JavaScript Basics', 'views' => 800, 'published_date' => '2023-03-20'],
];

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

echo "Sorted by Views (Descending):
";
print_r($articles);

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

echo "
Sorted by Published Date (Ascending):
";
print_r($articles);
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. It is particularly useful for sorting arrays of associative arrays or objects based on a specific property or complex custom logic. The comparison function should return 0 if elements are equal, a negative value if the first element should come before the second, and a positive value if it should come after. The spaceship operator (`<=>`) simplifies this comparison in PHP 7+.

Need help integrating this into your project?

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

Hire DigitalCodeLabs