Master PHP’s usort(): Custom Array Sorting Made Easy
This article explains how the PHP usort() function works, shows the required comparison function syntax, provides step‑by‑step code examples for sorting numeric arrays, associative arrays, and objects, and highlights important usage notes and pitfalls to ensure reliable custom array sorting.
PHP is a widely used programming language that offers many built‑in functions for developers. usort() is one of them, and its main purpose is to sort an array according to a user‑defined comparison function.
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;
}In this function, $a and $b represent the two elements being compared. The function should return 0 if they are equal, -1 if $a is smaller, and 1 if $a is larger.
Usage
Below is a basic example of using usort() to sort a numeric array:
$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] usort()can also sort arrays of strings or objects. For instance, to sort an array of student records by age:
$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 ascendingImportant Notes
The comparison function must be callable.
The function must return only 0, -1, or 1. usort() modifies the original array directly, so be aware of side effects.
If multiple elements are equal, usort() does not guarantee their relative order.
Conclusion
The usort() function is a common and powerful tool in PHP development for custom array sorting. By defining an appropriate comparison function and passing it to usort(), developers can sort numbers, strings, or complex objects efficiently, while keeping in mind the noted caveats.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
