Backend Development 6 min read

Using PHP usort() Function for Custom Array Sorting

This article explains the PHP usort() function, detailing its syntax, how to write custom comparison callbacks, and provides step‑by‑step examples for sorting numeric arrays, associative arrays of objects, and handling common pitfalls such as return values and in‑place array modification.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP usort() Function for Custom Array Sorting

PHP is a widely used programming language that provides many common functions for developers. The usort() function is one of them. Its main purpose is to sort an array according to a user‑defined comparison function.

The syntax of usort() is:

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

In this declaration, $array represents the array to be sorted, and $cmp_function is a callable comparison function. The function returns a boolean indicating whether the sorting succeeded.

Below is a detailed introduction to the usort() function.

Comparison Function

The comparison function passed to usort() must be callable, meaning it can be invoked. Typically the comparison function is defined when calling usort() , either as an anonymous function or by specifying a named function. For example, you can define a comparison function like this:

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

In this function, $a and $b are the two elements that usort() passes to the comparator. The function should return 0 if the elements are equal, -1 if $a is considered smaller than $b , and 1 if $a is larger.

Usage

Now we will see how to use usort() to sort an array. Suppose we have the following array:

$array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];

We can sort it with usort() by passing the name of the comparison function defined earlier:

usort($array, "cmp");

After executing the code, the sorted array is:

[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]

The usort() function can also sort strings, objects, and other data types. For example, consider an array of student objects:

$students = [
    ["name" => "Alice", "age" => 18],
    ["name" => "Bob",   "age" => 20],
    ["name" => "Charlie", "age" => 19],
];

To sort these students by age, we define a new comparison function:

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

Then we call usort() with this function:

usort($students, "cmp_age");

Running the code yields the students ordered from youngest to oldest:

[
    ["name" => "Alice",   "age" => 18],
    ["name" => "Charlie", "age" => 19],
    ["name" => "Bob",     "age" => 20],
];

Precautions

When using usort() , keep the following points in mind:

The comparison function must be callable.

The function must return only 0, -1, or 1.

usort() modifies the original array in place, so be aware of other references to the array.

If the array contains duplicate elements, usort() does not guarantee their relative order.

Summary

The usort() function is a commonly used PHP function that makes custom array sorting straightforward. To use it, define a comparison function and pass it to usort() . While there are some details to watch, employing usort() is generally simple and effective.

Rapid Introduction to PHP Practical Development

Scan the QR code to receive free learning materials

Backend Developmentphparray-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

login 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.