PHP

Sorting an Array of Associative Arrays by a Specific Key

Discover how to efficiently sort a complex PHP array containing multiple associative arrays based on the value of a specific key (e.g., 'price' or 'name').

<?php
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Desk Chair', 'price' => 150, 'category' => 'Furniture']
];

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

echo "Sorted by price (ascending):
";
print_r($products);

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

echo "
Sorted by name (descending):
";
print_r($products);
?>
How it works: This code demonstrates sorting an array of associative arrays using `usort`. `usort` sorts an array by values using a user-defined comparison function. The anonymous comparison function takes two elements (`$a` and `$b`) from the array and returns 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 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