PHP

Custom Sort Associative Array by Key in PHP

Discover how to sort an array of associative arrays in PHP using a custom comparison function with `usort()` or `uasort()` based on a specific key's value for flexible ordering.

<?php

$products = [
    ['id' => 1, 'name' => 'Laptop', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'price' => 75],
    ['id' => 4, 'name' => 'Monitor', 'price' => 300]
];

// 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 'name' in descending order
usort($products, function($a, $b) {
    return $b['name'] <=> $a['name']; // Descending name sort
});

echo "
Sorted by Name (Descending):
";
print_r($products);

/*
Output:
Sorted by Price (Ascending):
Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Mouse
            [price] => 25
        )

    [1] => Array
        (
            [id] => 3
            [name] => Keyboard
            [price] => 75
        )

    [2] => Array
        (
            [id] => 4
            [name] => Monitor
            [price] => 300
        )

    [3] => Array
        (
            [id] => 1
            [name] => Laptop
            [price] => 1200
        )

)

Sorted by Name (Descending):
Array
(
    [0] => Array
        (
            [id] => 4
            [name] => Monitor
            [price] => 300
        )

    [1] => Array
        (
            [id] => 2
            [name] => Mouse
            [price] => 25
        )

    [2] => Array
        (
            [id] => 1
            [name] => Laptop
            [price] => 1200
        )

    [3] => Array
        (
            [id] => 3
            [name] => Keyboard
            [price] => 75
        )

)
*/

?>
How it works: This snippet demonstrates how to perform custom sorting on an array of associative arrays in PHP using the `usort()` function. `usort()` takes the array and a callback function as arguments. The callback function compares two elements (`$a`, `$b`) from the array and should return -1 if `$a` is less than `$b`, 1 if `$a` is greater than `$b`, or 0 if they are equal. The PHP 7+ spaceship operator (`<=>`) simplifies this comparison. This allows for flexible sorting based on any key's value, in either ascending or descending order, making it highly versatile for data presentation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs