← Back to all snippets
PHP

Custom Sorting Associative Arrays with usort

Master custom sorting of complex PHP arrays, specifically arrays of associative arrays, using usort() with a user-defined comparison function.

<?php
$products = [
    ['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Book', 'price' => 20, 'category' => 'Books'],
    ['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['name' => 'Pen', 'price' => 5, 'category' => 'Stationery'],
];

// Sort by 'category' (ascending), then by 'price' (ascending)
usort($products, function($a, $b) {
    // First, compare by category
    if ($a['category'] !== $b['category']) {
        return strcmp($a['category'], $b['category']);
    }
    // If categories are the same, compare by price
    return $a['price'] <=> $b['price']; // PHP 7+ spaceship operator
});

print_r($products);
?>
How it works: This snippet demonstrates advanced sorting of an array containing associative arrays using `usort()`. It employs a custom comparison function to sort the `$products` array first by 'category' in ascending alphabetical order. If two products share the same category, it then sorts them by 'price' in ascending numerical order. The spaceship operator (`<=>`) introduced in PHP 7 simplifies numerical comparisons.

Need help integrating this into your project?

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

Hire DigitalCodeLabs