← Back to all snippets
PHP

Sort Array of Associative Arrays by a Key

Efficiently sort an array of associative arrays in PHP by the value of a specific key (e.g., 'price', 'name'), allowing both ascending and descending order.

<?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]
];

/**
 * Sorts an array of associative arrays by a specified key.
 * @param array $array The array to sort.
 * @param string $key The key to sort by.
 * @param string $order 'asc' for ascending, 'desc' for descending.
 */
function sortBySubkeyValue(array &$array, string $key, string $order = 'asc'): void
{
    usort($array, function ($a, $b) use ($key, $order) {
        $valueA = $a[$key] ?? null;
        $valueB = $b[$key] ?? null;

        if (is_numeric($valueA) && is_numeric($valueB)) {
            $cmp = ($valueA <=> $valueB);
        } else {
            $cmp = strcmp((string)$valueA, (string)$valueB);
        }

        return ($order === 'desc') ? -$cmp : $cmp;
    });
}

// Sort by price ascending
sortBySubkeyValue($products, 'price', 'asc');
echo "
Sorted by price (ASC):
";
print_r($products);

// Sort by name descending
sortBySubkeyValue($products, 'name', 'desc');
echo "
Sorted by name (DESC):
";
print_r($products);

/*
Output:
Sorted by price (ASC):
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 (DESC):
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 provides a reusable function `sortBySubkeyValue` to sort an array containing associative arrays (or objects) based on the value of a specified key. It uses `usort` with a custom comparison function. The comparison function dynamically handles both numeric and string values using the spaceship operator (`<=>`) for numbers and `strcmp` for strings, ensuring correct sorting. It also supports both ascending ('asc') and descending ('desc') orders.

Need help integrating this into your project?

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

Hire DigitalCodeLabs