usort()
usort() — Sort an array by values 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 values using a user-supplied comparison function to determine the order.
Signature
usort(array &$array, callable $callback): true callback(mixed $a, mixed $b): int
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| &$array | array | The input array. |
| $callback | callable | The 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) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $a = array(3, 2, 5, 6, 1); usort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n"; }
Output:
0: 1 1: 2 2: 3 3: 5 4: 6
Changelog
| Version | Change |
|---|---|
| 8.2.0 | The return type is true now; previously, it was bool. |
| 8.0.0 | If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page usort() (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.