usort
Sorts an array by a custom comparison rule.
Syntax
usort(array &$array, callable $callback): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being sorted. |
| $callback | callable | A function comparing two elements: returns a negative number, zero or a positive one. |
Return value
trueAlways `true`; the array itself is modified.
Examples
Sorting by a field:
<?php
$users = [['name' => 'Oleg', 'age' => 31], ['name' => 'Anna', 'age' => 25]];
usort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
echo implode(', ', array_column($users, 'name'));Output:
Anna, OlegDescending order — the arguments are swapped:
<?php
$numbers = [3, 10, 1];
usort($numbers, fn ($a, $b) => $b <=> $a);
echo implode(', ', $numbers);Output:
10, 3, 1Notes
The keys are replaced with numbers from zero. To keep the keys, use uasort().
See also
Related recipes
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.