PHP
Sort an Array of Objects or Associative Arrays by Custom Criteria
Discover how to sort a PHP array containing complex data structures like objects or associative arrays using a custom comparison function with `usort`.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 10],
['name' => 'Mouse', 'price' => 25, 'stock' => 50],
['name' => 'Keyboard', 'price' => 75, 'stock' => 25],
['name' => 'Monitor', 'price' => 300, 'stock' => 5]
];
echo "
Original Products:
";
print_r($products);
// Sort 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 by stock in descending order, then by name alphabetically for ties
usort($products, function($a, $b) {
if ($a['stock'] == $b['stock']) {
return $a['name'] <=> $b['name'];
}
return $b['stock'] <=> $a['stock']; // Descending stock
});
echo "
Sorted by Stock (Descending) then Name (Ascending):
";
print_r($products);
?>
How it works: `usort()` allows you to sort an array by a user-defined comparison function. This is crucial for arrays containing complex elements (like associative arrays or objects) where simple alphabetical or numerical sorting isn't sufficient. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered respectively less than, equal to, or greater than the second. The spaceship operator (`<=>`) in PHP 7+ simplifies numerical comparisons.