uasort
Sorts an array by a custom rule, keeping the keys.
Syntax
uasort(array &$array, callable $callback): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being sorted. |
| $callback | callable | A function comparing two elements. |
Return value
trueAlways `true`; the array itself is modified.
Examples
Sorting by a nested field while keeping the keys:
<?php
$users = [
'oleg' => ['age' => 31],
'anna' => ['age' => 25],
];
uasort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
echo implode(', ', array_keys($users));Output:
anna, olegNotes
usort() would replace the keys with numbers. uksort() sorts by key with a custom rule.
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.