Example 1 — Sort Keys by Length
The callback compares the length of two keys, so the shortest key comes first.
<?php
$fruits = ["banana" => 1, "fig" => 2, "apple" => 3];
uksort($fruits, fn($a, $b) => strlen($a) <=> strlen($b));
foreach ($fruits as $name => $count) {
echo $name, " => ", $count, PHP_EOL;
} How It Works
- The keys banana, fig and apple have 6, 3 and 5 letters.
- strlen() gives the length of each key inside the callback.
- <=> compares the two lengths, so the shortest key goes first.
- The values stay attached to their own keys.

