PHP

Sorting Associative Arrays by a Specific Key

Sort an array of associative arrays or objects in PHP based on the value of a specified key, allowing for custom ordering of complex datasets, whether ascending or descending.

<?php
// Using usort for simple sorting by a single key
function sortAssociativeArrayByKey(array &$array, string $key, bool $descending = false): void
{
    usort($array, function ($a, $b) use ($key, $descending) {
        if (!isset($a[$key]) || !isset($b[$key])) {
            return 0; // Handle cases where key might be missing
        }
        $valueA = $a[$key];
        $valueB = $b[$key];

        if (is_numeric($valueA) && is_numeric($valueB)) {
            return $descending ? ($valueB <=> $valueA) : ($valueA <=> $valueB);
        } else {
            return $descending ? strnatcmp($valueB, $valueA) : strnatcmp($valueA, $valueB);
        }
    });
}

$users = [
    ['name' => 'Charlie', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 35]
];

echo "Sorted by age (asc):
";
sortAssociativeArrayByKey($users, 'age');
print_r($users);

echo "
Sorted by name (desc):
";
sortAssociativeArrayByKey($users, 'name', true);
print_r($users);

/*
Output:
Sorted by age (asc):
Array
(
    [0] => Array
        (
            [name] => Alice
            [age] => 25
        )

    [1] => Array
        (
            [name] => Charlie
            [age] => 30
        )

    [2] => Array
        (
            [name] => Bob
            [age] => 35
        )

)

Sorted by name (desc):
Array
(
    [0] => Array
        (
            [name] => Charlie
            [age] => 30
        )

    [1] => Array
        (
            [name] => Bob
            [age] => 35
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 25
        )

)
*/
?>
How it works: The `sortAssociativeArrayByKey` function sorts an array of associative arrays in place based on the value of a specified key. It uses `usort` with a custom comparison function (a closure) that accesses the target key from each pair of elements. The comparison logic handles both numeric and string values, using the spaceship operator (`<=>`) for numbers and `strnatcmp` for natural string comparison, and supports both ascending and descending order based on the `$descending` parameter.

Need help integrating this into your project?

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

Hire DigitalCodeLabs