PHP

Sort Associative Array of Arrays by a Specific Key

Learn how to sort a list of associative arrays based on the value of a particular key within each sub-array using PHP's `usort` function.

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

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

print_r($users);

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

print_r($users);
How it works: This snippet demonstrates sorting an array where each element is itself an associative array. Using `usort()` with a custom comparison function (a lambda function here), you can specify which key to sort by and whether the order should be ascending or descending. The spaceship operator (`<=>`) simplifies the comparison logic for numeric or string values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs