PHP

Custom Sort PHP Associative Arrays by Key Value

Master custom sorting of an array of associative arrays in PHP using `usort` or `uasort`, allowing you to order data based on any specific key.

<?php

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

// Sort by 'age' in ascending order
usort($users, function($a, $b) {
    return $a['age'] <=> $b['age'];
});

echo "Sorted by age (ascending):
";
print_r($users);

// Sort by 'name' in descending order
usort($users, function($a, $b) {
    return $b['name'] <=> $a['name'];
});

echo "
Sorted by name (descending):
";
print_r($users);

// Expected Output (for age sort):
// Array
// (
//     [0] => Array ([id] => 1, [name] => Bob, [age] => 25)
//     [1] => Array ([id] => 4, [name] => David, [age] => 25)
//     [2] => Array ([id] => 3, [name] => Alice, [age] => 30)
//     [3] => Array ([id] => 2, [name] => Charlie, [age] => 35)
// )
How it works: The `usort()` function allows sorting an array by a user-defined comparison function. The comparison function takes two elements of the array (`$a` and `$b`) and should return `0` if they are equal, `-1` if `$a` should come before `$b`, or `1` if `$a` should come after `$b`. The spaceship operator (`<=>`) simplifies this comparison for numerical or string values, returning `-1`, `0`, or `1` directly. This enables flexible sorting based on any key within the associative array elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs