Using PHP usort() to Sort Arrays with Custom Comparison Functions
This article explains how PHP's usort() function sorts arrays using a user‑defined comparison function, covering its syntax, example implementations for numeric and associative arrays, and important usage considerations, including code samples, handling of return values, and common pitfalls such as stability and side effects.
PHP provides the usort() function to sort arrays based on a user‑defined comparison function. The function signature is:
usort(array $array, callable $cmp_function): boolThe comparison function must be callable and return 0, -1, or 1. A typical example is:
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}Using this, a numeric array can be sorted as follows:
$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]For associative arrays, such as a list of students, you can sort by a specific field (e.g., age) with a custom comparator:
$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 ascendingKey points to remember when using usort() :
The comparison function must be callable.
It must return only 0, -1, or 1.
usort() modifies the original array in place.
The function does not guarantee stable ordering for equal elements.
In summary, usort() is a versatile PHP function for custom array sorting, requiring a proper comparison callback and awareness of its side effects.
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.