PHP

Sort Associative Array by Key in PHP

Learn how to sort an array of associative arrays (or objects) in PHP based on the value of a specific nested key, using `usort` with a custom comparison function for flexible ordering.

<?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 based on a specific key's value using PHP's `usort()` function. `usort()` takes the array and a callback function for comparison. The callback function receives two elements ($a, $b) from the array and should return -1 if $a comes before $b, 1 if $a comes after $b, and 0 if they are equal. The PHP 7+ spaceship operator (`<=>`) simplifies this comparison, returning -1, 0, or 1 directly. By changing which keys are compared and the order of $a and $b, you can achieve both ascending and descending sorts on any desired column.

Need help integrating this into your project?

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

Hire DigitalCodeLabs