Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

uksort

Sorts an array by keys using your own comparison function.

Syntax

uksort(array &$array, callable $callback): true

Parameters

ParameterTypeDescription
$arrayarrayThe array; changed in place.
$callbackcallableA 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, banana

Notes

The comparison function returns a negative number, zero or a positive one — the <=> operator is the handiest.

See also

  • usort — Sorts an array by a custom comparison rule.
  • uasort — Sorts an array by a custom rule, keeping the keys.
  • ksort — Sorts an array by key.

Related recipes

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.