Using usort() to Sort an Array by a Custom Function in PHP


Sort an array using a user-defined comparison function.

Source Code

$people = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 22],
    ['name' => 'Gary', 'age' => 32]
];
usort($people, function ($a, $b) {
    return $a['age']  $b['age'];
});
print_r($people); // Sorted by age
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments