How to Use PHP's usort() Function for Custom Array Sorting
This article explains the PHP usort() function, its syntax, how to write comparison callbacks, and demonstrates sorting numeric arrays, strings, and objects such as student records by age, while highlighting important usage considerations and pitfalls.
PHP is a widely used programming language that provides many built‑in functions for developers, one of which is usort() . The usort() function sorts an array according to a user‑defined comparison function.
The syntax of usort() is:
usort(array $array, callable $cmp_function): boolIn this signature, $array is the array to be sorted and $cmp_function is a callable that compares two elements. The function returns a boolean indicating whether the sort succeeded.
Comparison Function
The comparison function passed to usort() must be callable. It is usually defined as an anonymous function or a named function. For example:
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}The function receives two values ( $a and $b ) from the array. It must return 0 if the values are equal, -1 if $a is considered smaller, or 1 if $a is larger.
Usage
To sort a numeric array with usort() :
$array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];Apply the comparison function:
usort($array, "cmp");The resulting sorted array is:
[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]usort() can also sort strings, objects, or associative arrays. For instance, to sort an array of student records by age:
$students = [
["name" => "Alice", "age" => 18],
["name" => "Bob", "age" => 20],
["name" => "Charlie", "age" => 19],
];Define a comparison function for the age field:
function cmp_age($a, $b) {
if ($a["age"] == $b["age"]) {
return 0;
}
return ($a["age"] < $b["age"]) ? -1 : 1;
}Sort the students:
usort($students, "cmp_age");After sorting, the array becomes:
[
["name" => "Alice", "age" => 18],
["name" => "Charlie", "age" => 19],
["name" => "Bob", "age" => 20],
];Precautions
When using usort() , keep in mind:
The comparison function must be callable.
The function must return only 0, -1, or 1.
usort() modifies the original array in place, so be aware of other references.
If the array contains equal elements, usort() does not guarantee their relative order.
Summary
The usort() function is a common PHP utility for custom array sorting. By defining an appropriate comparison callback and passing it to usort() , developers can sort numbers, strings, or complex objects efficiently, while observing the noted caveats.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.