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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using usort() to Sort Arrays with a User-Defined Comparison Function in PHP

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: 6
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendprogrammingarray sortingusort
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.