← Back to all snippets
PHP

Sorting Associative Arrays by a Key in PHP

Learn how to sort an array of associative arrays or objects based on the value of a specific key using `usort()` in PHP.

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

usort($users, function($a, $b) {
    return $a['age'] <=> $b['age']; // Spaceship operator for comparison
});

print_r($users);
?>
How it works: This snippet demonstrates sorting an array of associative arrays based on a specific key, 'age' in this case, using `usort()`. The `usort()` function takes a custom comparison callback. The spaceship operator (`<=>`) within the callback efficiently compares the 'age' values, returning -1, 0, or 1 to determine the sort order.

Need help integrating this into your project?

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

Hire DigitalCodeLabs