usort()
Learn how PHP's usort() function sorts an array in place using a user-defined comparison callback, with examples for strings, numbers, and objects.
PHP's usort() function sorts an array using a comparison function that you write. Where built-in functions like sort() only know how to order values one way (ascending, by value), usort() lets you express any rule at all — sort objects by a property, numbers in a custom order, or strings by a tie-breaking rule. This page explains how the comparison callback works, walks through string, numeric, and object examples, and covers the gotchas that trip people up.
What is usort() function?
The usort() function is a built-in PHP function that sorts an array using your own comparison rule. Unlike standard sorting functions that sort by value or key in ascending/descending order, usort() requires a callback to define the comparison logic. It modifies the original array in place and returns true on success or false on failure (so you sort the array, you do not capture the return value as the sorted result).
How the comparison callback works
The callback receives two elements, $a and $b, and must return an integer that tells usort() their relative order:
- a negative number if
$ashould come before$b, - a positive number if
$ashould come after$b, 0if they are considered equal.
Since PHP 7 the spaceship operator <=> does exactly this in one step: $a <=> $b returns -1, 0, or 1. Most comparison callbacks reduce to a single return using it.
Note: usort() is not a stable sort. If two elements compare as equal, their original relative order is not guaranteed to be preserved. As of PHP 8.0 sorting is stable, but earlier versions are not. Additionally, usort() reindexes the array sequentially starting from 0, so any original keys are lost — use uasort() if you need to keep key associations.
Syntax
The syntax for the usort() function is as follows:
The syntax of usort() function in PHP
usort($array, $callback);Here, $array is the array that you want to sort, and $callback is the callback function that defines the custom sorting rules.
Parameters and Return Value
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to sort. |
$callback | callable | A user-defined comparison function. |
Return Value: Returns true on success or false on failure.
Example Usage
Let's take a look at an example to see how the usort() function works. Suppose we have an array of names that we want to sort in alphabetical order, but with a custom rule that all names starting with "J" should come first.
How to use usort() function in PHP?
In this example, we define a callback function that compares two names and returns -1, 0, or 1 based on the custom sorting rules. If the first letter of $a is "J" and the first letter of $b is not "J", then $a comes before $b. If the first letter of $a is not "J" and the first letter of $b is "J", then $b comes before $a. If both names start with "J" or both do not start with "J", then we use the modern PHP spaceship operator (<=>) to compare the names alphabetically.
After executing this code, the $names array will be sorted as follows:
Array
(
[0] => Jack
[1] => Jenny
[2] => John
[3] => Adam
[4] => Bob
)Sorting objects or arrays by a field
The most common real-world use of usort() is ordering a list of records (associative arrays or objects) by one of their fields — something sort() cannot do. Here we sort a list of products by price, ascending:
<?php
$products = [
["name" => "Book", "price" => 15],
["name" => "Pen", "price" => 2],
["name" => "Laptop", "price" => 900],
];
usort($products, fn ($a, $b) => $a["price"] <=> $b["price"]);
print_r(array_column($products, "name"));The whole comparison is a single spaceship expression. The output, cheapest first:
Array
(
[0] => Pen
[1] => Book
[2] => Laptop
)To sort descending, just swap the operands: $b["price"] <=> $a["price"].
Common gotchas
- Return value misuse.
usort()returnstrue/false, not the sorted array. Writing$sorted = usort($arr, ...)gives youtrue, not your data. The array is sorted in place. - Keys are reset. Original keys are discarded and replaced with
0, 1, 2, …. Useuasort()to preserve keys, oruksort()to sort by keys. - Returning a bool from the callback. Returning
$a > $b(a boolean) works for ascending order by accident but breaks for descending and equal cases. Always return an integer — prefer<=>.
Related functions
sort()— sort an array by value, ascending, with no callback.asort()— sort by value while preserving keys.ksort()— sort by key.uasort()— likeusort()but preserves key associations.uksort()— sort by keys using a custom callback.
Conclusion
In this article, we discussed the usort() function in PHP and demonstrated how it can be used to sort arrays with custom sorting rules. By defining a callback function, you can sort arrays in any order you desire, based on your own custom rules. This function can be especially useful in situations where the built-in sorting functions in PHP are not sufficient for your needs. With the usort() function, you have complete control over how your arrays are sorted.