uksort
Sorts an array by keys using your own comparison function.
Syntax
uksort(array &$array, callable $callback): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array; changed in place. |
| $callback | callable | A function comparing two keys. |
Return value
trueAlways `true`.
Examples
Keys by length:
<?php
$data = ['banana' => 1, 'fig' => 2, 'apple' => 3];
uksort($data, fn ($a, $b) => strlen($a) <=> strlen($b));
echo implode(', ', array_keys($data));Output:
fig, apple, bananaNotes
The comparison function returns a negative number, zero or a positive one — the <=> operator is the handiest.
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.