uksort()

uksort() — Sort an array by keys using a user-defined comparison function.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Sorts array in place by keys using a user-supplied comparison function to determine the order.

Signature

uksort(array &$array, callable $callback): true callback(mixed $a, mixed $b): int

Parameters

ParameterTypeWhat it takes
&$arrayarrayThe input array.
$callbackcallableThe comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return value

Always returns true.

Example

A runnable snippet:

function cmp($a, $b) { $a = preg_replace('@^(a|an|the) @', '', $a); $b = preg_replace('@^(a|an|the) @', '', $b); return strcasecmp($a, $b); } $a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4); uksort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n"; }

Output:

an apple: 3 a banana: 4 the Earth: 2 John: 1

Changelog

VersionChange
8.2.0The return type is true now; previously, it was bool.
8.0.0If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING.

See also

usort(), uasort()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page uksort() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.