uasort()
uasort() — Sort an array with a user-defined comparison function and maintain index association.
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 such that its keys maintain their correlation with the values they are associated with, using a user-defined comparison function.
Signature
uasort(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:
// Comparison function function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } // Array to be sorted $array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4); print_r($array); // Sort and print the resulting array uasort($array, 'cmp'); print_r($array);
Output:
Array ( [a] => 4 [b] => 8 [c] => -1 [d] => -9 [e] => 2 [f] => 5 [g] => 3 [h] => -4 ) Array ( [d] => -9 [h] => -4 [c] => -1 [e] => 2 [g] => 3 [a] => 4 [f] => 5 [b] => 8 )
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 uasort() (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.