Using usort() to Sort Arrays with a User-Defined Comparison Function in PHP
The article explains PHP's usort() function, detailing its purpose, parameters, return values, and providing a complete example with code and output to demonstrate how to sort an array using a custom comparison callback.
The PHP usort() function sorts the values of an array using a user‑defined comparison function, allowing custom ordering criteria.
Parameters: array &$array – the input array to be sorted; callable $cmp_function – a function that returns an integer less than, equal to, or greater than zero when the first argument is respectively less than, equal to, or greater than the second.
Return value: TRUE on success, FALSE on failure.
Example:
<?php
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value
";
}
?>Output:
0: 1
1: 2
2: 3
3: 5
4: 6Signed-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.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.
