PHP

Sort PHP Array with Custom Comparison Function (usort)

Implement flexible sorting for PHP arrays using `usort()` and a custom comparison function. Sort by multiple criteria, specific object properties, or complex logic.

<?php
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Book', 'price' => 25, 'category' => 'Books'],
    ['name' => 'Mouse', 'price' => 30, 'category' => 'Electronics'],
    ['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics']
];

// Sort products first by category (alphabetically), then by price (ascending)
usort($products, function ($a, $b) {
    // Compare by category
    $categoryComparison = strcmp($a['category'], $b['category']);
    if ($categoryComparison !== 0) {
        return $categoryComparison;
    }
    // If categories are the same, compare by price
    return $a['price'] <=> $b['price']; // Spaceship operator for comparison
});

print_r($products);
/*
$products will be sorted as:
[
    ['name' => 'Book', 'price' => 25, 'category' => 'Books'],
    ['name' => 'Mouse', 'price' => 30, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics'],
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics']
]
*/
?>
How it works: The `usort()` function allows for custom sorting of an array by providing a user-defined comparison function. This function takes two array elements as arguments and must return -1, 0, or 1 based on their desired order. This snippet demonstrates sorting an array of products by category first, then by price, showcasing its power for complex multi-criteria sorting.

Need help integrating this into your project?

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

Hire DigitalCodeLabs