In PHP, uasort() sorts an array by its values using your own comparison function, and keeps the keys.
The "u" stands for user-defined and the "a" stands for association (keys kept). Use it when the normal sorting rules do not fit, such as sorting products by price or names by length, while keeping each key linked to its value.
Syntax
Call uasort() with the values you need. Start with this line.
PHP
uasort($ages, fn($a, $b) => $a <=> $b);
Call
What it does
uasort($ages, fn($a, $b) => $a <=> $b)
Sorts the values from low to high and keeps the keys.
uasort($ages, fn($a, $b) => $b <=> $a)
Swapping $a and $b sorts from high to low.
uasort($items, "strcmp")
You can also pass the name of an existing function.
The callback receives two values and must return a negative number, zero or a positive number. The spaceship operator <=> does this for you. uasort() changes the original array and returns true.
Library declarations
PHP
uasort(array &$array, callable $callback): true
Parameters
Parameter
Description
array
Required. The array to sort. It is passed by reference and changed in place.
callback
Required. A function that takes two values and returns an integer less than, equal to or greater than zero. This sets the order.
Return Value
Return Value
Description
true
Always returns true. The sorted result is stored in the array you passed in.
PHP Examples
Example 1 — Sort Values Low to High and Keep Keys
The spaceship operator <=> compares two values and gives -1, 0 or 1.