PHP
Custom Sorting an Array of Associative Arrays
Learn how to perform custom sorting on an array of associative arrays or objects in PHP using `usort()` with a user-defined comparison function.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 15],
['name' => 'Mouse', 'price' => 25, 'stock' => 50],
['name' => 'Keyboard', 'price' => 75, 'stock' => 30],
['name' => 'Monitor', 'price' => 300, 'stock' => 10],
];
echo "Products (unsorted):
";
foreach ($products as $product) {
echo "- " . $product['name'] . " (Price: $" . $product['price'] . ", Stock: " . $product['stock'] . ")
";
}
// Sort products by price in ascending order
usort($products, function($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
});
echo "
Products (sorted by price ascending):
";
foreach ($products as $product) {
echo "- " . $product['name'] . " (Price: $" . $product['price'] . ")
";
}
// Sort products by stock in descending order
usort($products, function($a, $b) {
return $b['stock'] <=> $a['stock']; // PHP 7+ spaceship operator
});
echo "
Products (sorted by stock descending):
";
foreach ($products as $product) {
echo "- " . $product['name'] . " (Stock: " . $product['stock'] . ")
";
}
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. This is particularly useful for sorting arrays of associative arrays or objects based on a specific property or a complex custom logic. The comparison function should return 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.