PHP
Sort Associative Array by Inner Key Value
Learn how to sort an array of associative arrays in PHP based on the value of a specific key within each nested array, useful for ordered lists.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'price' => 75],
['id' => 4, 'name' => 'Monitor', 'price' => 300],
];
// Sort products by 'price' in ascending order
usort($products, function($a, $b) {
return $a['price'] <=> $b['price']; // PHP 7+ spaceship operator
});
echo "Sorted by price (ascending):
";
print_r($products);
// Sort products by 'name' in descending order
usort($products, function($a, $b) {
return $b['name'] <=> $a['name']; // Swap $a and $b for descending
});
echo "
Sorted by name (descending):
";
print_r($products);
?>
How it works: This snippet demonstrates how to sort an array of associative arrays using `usort()`. A custom comparison function is provided, which compares the values of a specified key (e.g., 'price' or 'name') from two elements. The spaceship operator (`<=>`) in PHP 7+ simplifies the comparison logic, returning -1, 0, or 1 based on whether the first operand is less than, equal to, or greater than the second.