PHP
Sort Associative Arrays by a Specific Key Value
Master sorting an array of associative arrays in PHP using `usort`, allowing you to define a custom comparison logic based on the value of a chosen key.
<?php
$items = [
['name' => 'Apple', 'price' => 1.50, 'quantity' => 50],
['name' => 'Banana', 'price' => 0.75, 'quantity' => 120],
['name' => 'Cherry', 'price' => 3.00, 'quantity' => 30],
['name' => 'Date', 'price' => 2.25, 'quantity' => 80]
];
// Sort items by 'price' in ascending order
usort($items, function($a, $b) {
return $a['price'] <=> $b['price']; // PHP 7+ spaceship operator
});
print_r($items);
/* Output:
Array
(
[0] => Array
(
[name] => Banana
[price] => 0.75
[quantity] => 120
)
[1] => Array
(
[name] => Apple
[price] => 1.5
[quantity] => 50
)
[2] => Array
(
[name] => Date
[price] => 2.25
[quantity] => 80
)
[3] => Array
(
[name] => Cherry
[price] => 3
[quantity] => 30
)
)*/
How it works: This snippet demonstrates how to sort an array of associative arrays based on the value of a specific key. The `usort()` function sorts an array by values using a user-defined comparison function. The anonymous function takes two elements (`$a` and `$b`) from the array and compares their 'price' values using the spaceship operator (`<=>`). This operator returns -1 if `$a` is less than `$b`, 0 if they are equal, and 1 if `$a` is greater than `$b`, effectively sorting the array by price in ascending order. Note that `usort` sorts the array in-place.