← Back to all snippets
PHP

Sort Associative Array by Key Value

Sort an array of associative arrays based on the values of a specific key (e.g., sorting a list of products by price or name) in ascending or descending order.

function sortArrayOfAssociativeArrays(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; // Or handle error
        }
        $valA = $a[$key];
        $valB = $b[$key];

        if ($valA == $valB) {
            return 0;
        }

        if ($descending) {
            return ($valA < $valB) ? 1 : -1;
        } else {
            return ($valA < $valB) ? -1 : 1;
        }
    });
}

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

sortArrayOfAssociativeArrays($users, 'age');
// print_r($users);
/* Output (sorted by age ascending):
Array
(
    [0] => Array ( [id] => 1, [name] => 'Bob', [age] => 25 )
    [1] => Array ( [id] => 3, [name] => 'Alice', [age] => 30 )
    [2] => Array ( [id] => 2, [name] => 'Charlie', [age] => 35 )
)
*/

sortArrayOfAssociativeArrays($users, 'name', true); // Sort by name descending
// print_r($users);
/* Output (sorted by name descending):
Array
(
    [0] => Array ( [id] => 2, [name] => 'Charlie', [age] => 35 )
    [1] => Array ( [id] => 1, [name] => 'Bob', [age] => 25 )
    [2] => Array ( [id] => 3, [name] => 'Alice', [age] => 30 )
)
*/
How it works: This function sorts an array of associative arrays in-place (`&$array`) based on the value of a specified `$key`. It uses `usort` with an anonymous comparison function. The comparison function compares the values of the given key from two elements (`$a` and `$b`) and returns -1, 0, or 1 based on the desired sort order (ascending by default, or descending if `$descending` is true).

Need help integrating this into your project?

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

Hire DigitalCodeLabs