Master PHP’s usort(): Custom Sorting Made Simple

This guide explains how PHP's usort() function sorts arrays using a user‑defined comparison callback, covering its signature, how to write comparison functions, examples for numeric and associative arrays, and important considerations for reliable custom sorting.

php Courses
php Courses
php Courses
Master PHP’s usort(): Custom Sorting Made Simple

PHP provides many built‑in functions; usort() sorts an array according to a user‑defined comparison function.

Function signature

usort(array $array, callable $cmp_function): bool

The first argument is the array to be sorted, the second is a callable that receives two elements and must return 0, -1, or 1.

Comparison function

The comparison function must be callable. A typical example:

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

Returning 0 indicates equality, -1 means the first argument is smaller, and 1 means it is larger.

Basic usage

Sorting 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]

Sorting associative arrays

When sorting an array of associative arrays (e.g., students), define a comparator that examines a specific key:

function cmp_age($a, $b) {
    if ($a["age"] == $b["age"]) {
        return 0;
    }
    return ($a["age"] < $b["age"]) ? -1 : 1;
}
usort($students, "cmp_age");

After execution the $students array is ordered by the age field from smallest to largest.

Important notes

The comparison function must be callable.

It must return only 0, -1, or 1. usort() sorts the array in place, so the original array is modified.

If multiple elements compare as equal, their relative order is not guaranteed.

Conclusion

usort()

is a versatile PHP function for custom sorting of arrays, strings, objects, or any data structure where a user‑defined comparator can be applied.

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.

PHParray sortingusortcustom comparator
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.