Using PHP usort() Function to Sort Arrays with Custom Comparison Functions
This article explains the PHP usort() function, its syntax, how to write custom comparison callbacks, and provides practical examples for sorting numeric arrays, associative arrays of objects, and handling important considerations such as return values, mutability, and stability.
PHP is a widely used programming language that provides many built‑in functions for developers, among which usort() is used to sort an array according to a user‑defined comparison function.
The syntax of usort() is:
<code>usort(array $array, callable $cmp_function): bool</code>Here $array is the array to be sorted and $cmp_function is a callable that compares two elements and returns 0, -1, or 1.
Comparison Function
The comparison function must be callable; it can be an anonymous function or a named function. For example:
<code>function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}</code>The function receives two values ( $a and $b ) from the array and should return 0 if they are equal, -1 if $a is smaller, and 1 if $a is larger.
Usage
To sort a numeric array:
<code>$array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
usort($array, "cmp");
// Result: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]</code>The same function can sort strings, objects, or associative arrays. For example, sorting an array of student records by age:
<code>$students = [
["name" => "Alice", "age" => 18],
["name" => "Bob", "age" => 20],
["name" => "Charlie", "age" => 19],
];
function cmp_age($a, $b) {
if ($a["age"] == $b["age"]) {
return 0;
}
return ($a["age"] < $b["age"]) ? -1 : 1;
}
usort($students, "cmp_age");
// Result: sorted by age ascending
</code>Precautions
The comparison function must be callable.
It must return only 0, -1, or 1.
usort() modifies the original array in place.
If multiple elements are equal, their relative order is not guaranteed.
Summary
The usort() function is a common PHP utility for sorting arrays with custom logic; by defining an appropriate comparison callback and passing it to usort() , developers can sort numbers, strings, or complex structures efficiently, while being mindful of the function’s mutability and stability characteristics.
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.