In PHP, usort() sorts the values of an array using your own comparison function and gives them new keys 0, 1, 2 and so on.
Use usort() when the normal sort() does not fit, for example when you want to sort users by age, words by length, or products by price. You write a small function that says which of two values should come first.
Syntax
Call usort() with the values you need. Start with this line.
The callback receives two values and must return a negative number, zero or a positive number. usort() changes the original array and returns true. Since PHP 8.0 the sort is stable, so equal items keep their original order.
Library declarations
PHP
usort(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 Numbers from High to Low
The callback compares two numbers. Writing $b <=> $a puts the larger one first.
$users holds three small arrays with a name and an age.
The callback compares the "age" field of the two users it receives.
usort() orders the users from the youngest to the oldest.
The foreach loop prints each user in the new order.
Frequently Asked Questions
It sorts the values of an array with a comparison function that you write, and renumbers the keys from 0.
sort() uses PHP's built-in comparison rules. usort() lets you define your own, which is needed for records, custom orders and special rules.
usort() replaces the keys with 0, 1, 2. uasort() keeps the keys.
A negative number if the first value goes first, zero if they are equal, and a positive number if the second value goes first. The <=> operator does exactly this.
No. It changes the array you pass in and returns true.