PHP usort

Summary: in this tutorial, you’ll learn how to use the PHP usort() function to sort an array using a user-defined comparison function.

Introduction to the PHP usort() function

So far, you learned how to sort an array using a built-in comparison operator.

For example, when you use the sort() function to sort an array of numbers, PHP uses the built-in comparison operator to compare the numbers.

To specify a custom comparison function for sorting, you use the usort() function:

usort(array &$array, callable $callback): boolCode language: PHP (php)

The usort() function has two parameters:

  • $array is the input array.
  • $callback is the custom comparison function.

The usort() function returns true on success or false or failure.

The $callback has the following syntax:

callback(mixed $x, mixed $y): intCode language: PHP (php)

The $callback function has two parameters which are the array elements to compare.

The $callback function compares two elements ($x and $y) and returns an integer value:

  • zero (0) means $x is equal to $y.
  • a negative number means $x is before $y.
  • a positive number means $x is after $y.

PHP usort() function examples

Let’s take some examples of using the usort() function.

1) Using the PHP usort() function to sort an array of numbers

The following example illustrates how to use the usort() function to sort an array of numbers:

<?php

$numbers = [2, 1, 3];

usort($numbers, function ($x, $y) {
    if ($x === $y) {
        return 0;
    }
    return $x < $y ? -1 : 1;
});

print_r($numbers);Code language: PHP (php)

Output:

Array
(
    [0] => 1   
    [1] => 2   
    [2] => 3   
)    Code language: PHP (php)

How it works.

  • First, define an array of three numbers 2, 1, and 3.
  • Second, use the usort() function to sort the $numbers array. The callback function returns 0 if two numbers are equal, -1 if the first number is less than the second one, and 1 if the first number is greater than the second one.

To sort the elements of the array in descending order, you just need to change the logic in the comparison function like this:

<?php

$numbers = [2, 1, 3];

usort($numbers, function ($x, $y) {
    if ($x === $y) {
        return 0;
    }
    return $x < $y ? 1 : -1;
});

print_r($numbers);Code language: PHP (php)

If you use PHP 7 or newer, you can use the spaceship operator (<=>) to make the code more concise:

$x <=> $yCode language: PHP (php)

The spaceship operator compares two expressions and returns -1, 0, or 1 when $x is respectively less than, equal to, or greater than $y. For example:

<?php

$numbers = [2, 1, 3];

usort($numbers, function ($x, $y) {
    return $x <=> $y;
});

print_r($numbers);Code language: PHP (php)

If the callback is simple, you can use an arrow function like this:

<?php

$numbers = [2, 1, 3];
usort($numbers, fn ($x, $y) =>  $x <=> $y);

print_r($numbers);Code language: PHP (php)

Note that PHP introduced the arrow functions since PHP 7.4.

2) Using the PHP usort() function to sort an array of strings by length

The following example uses the usort() function to sort an array of names by length:

<?php

$names = [ 'Alex', 'Peter',  'John' ];
usort($names, fn($x,$y) => strlen($x) <=> strlen($y));

var_dump($names);Code language: PHP (php)

Output:

Array(3) 
{
    [0]=>  string(4) "Alex"
    [1]=>  string(4) "John"
    [2]=>  string(5) "Peter"
}Code language: PHP (php)

3) Using the PHP usort() function to sort an array of objects

The following example uses the usort() function to sort an array of Person objects by the age property.

<?php

class Person
{
    public $name;
    public $age;

    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

$group = [
    new Person('Bob', 20),
    new Person('Alex', 25),
    new Person('Peter', 30),
];

usort($group, fn($x, $y) => $x->age <=> $y->age);

print_r($group);Code language: PHP (php)

Output:

Array
(
    [0] => Person Object
        (
            [name] => Bob
            [age] => 20
        )
    [1] => Person Object
        (
            [name] => Alex
            [age] => 25
        )
    [2] => Person Object
        (
            [name] => Peter
            [age] => 30
        )
)Code language: PHP (php)

How it works.

  • First, define a Person class that has two properties: name and age.
  • Second, define the $group array that holds the Person objects.
  • Third, use the usort() function to sort the Person objects of the $group array. The usort() function uses a comparison function that compares the age of two Person objects.

If you want to sort the Person objects by name, you can compare the $name in the comparison like this:

usort($group, fn($x, $y) => $x->name <=> $y->name);Code language: PHP (php)

Using a static method as a callback

The following example uses a static method of class as a callback for the usort() function:

<?php

class Person
{
    public $name;

    public $age;

    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

class PersonComparer
{
    public static function compare(Person $x, Person $y)
    {
        return $x->age <=> $y->age;
    }
}

$group = [
    new Person('Bob', 20),
    new Person('Alex', 25),
    new Person('Peter', 30),
];

usort($group, ['PersonComparer', 'compare']);

print_r($group);Code language: PHP (php)

In this example, we define the PersonComparer class that contains the compare() static method.

The compare() static method compares two Person objects by age using the spaceship operator.

To use the compare() static method of the PersonComparer class as the callback the usort() function, you pass an array that contains two elements:

usort($group, ['PersonComparer', 'compare']);Code language: PHP (php)

The first element is the class name and the second one is the static method.

Summary

  • Use the PHP usort() function to sort an array using a user-defined comparison function.
Did you find this tutorial useful?