Using PHP usort() Function to Sort Arrays with Custom Comparison Functions

This article explains the PHP usort() function, its syntax, how to write custom comparison callbacks, and provides practical examples for sorting numeric arrays, associative arrays of objects, and handling important considerations such as return values, mutability, and stability.

php Courses
php Courses
php Courses
Using PHP usort() Function to Sort Arrays with Custom Comparison Functions

PHP is a widely used programming language that provides many built‑in functions for developers, among which usort() is used to sort an array according to a user‑defined comparison function.

The syntax of usort() is:

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

Here $array is the array to be sorted and $cmp_function is a callable that compares two elements and returns 0, -1, or 1.

Comparison Function

The comparison function must be callable; it can be an anonymous function or a named function. For example:

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

The function receives two values ( $a and $b) from the array and should return 0 if they are equal, -1 if $a is smaller, and 1 if $a is larger.

Usage

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]

The same function can sort strings, objects, or associative arrays. For example, sorting 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 ascending

Precautions

The comparison function must be callable.

It must return only 0, -1, or 1. usort() modifies the original array in place.

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

Summary

The usort() function is a common PHP utility for sorting arrays with custom logic; by defining an appropriate comparison callback and passing it to usort(), developers can sort numbers, strings, or complex structures efficiently, while being mindful of the function’s mutability and stability characteristics.

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 sortingusortcomparison-function
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.