PHP

Custom Sort Associative Arrays by Value

Learn to sort PHP associative arrays based on custom comparison logic using uasort, perfect for ordering complex data structures by specific criteria.

<?php
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'stock' => 10],
    ['name' => 'Mouse', 'price' => 25, 'stock' => 50],
    ['name' => 'Keyboard', 'price' => 75, 'stock' => 20],
    ['name' => 'Monitor', 'price' => 300, 'stock' => 5]
];

// Sort by 'price' in ascending order
uasort($products, function($a, $b) {
    return $a['price'] <=> $b['price'];
});

echo "Sorted by Price (Ascending):
";
print_r($products);

// Sort by 'stock' in descending order
uasort($products, function($a, $b) {
    return $b['stock'] <=> $a['stock'];
});

echo "
Sorted by Stock (Descending):
";
print_r($products);
?>
How it works: uasort() sorts an associative array by its values, maintaining key-value associations. It takes a callback function for custom comparison logic, where the spaceship operator (<=>) simplifies returning -1, 0, or 1 based on comparison. This allows flexible sorting of complex data structures like arrays of objects or records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs