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): boolThe usort() function has two parameters:
$arrayis the input array.$callbackis 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): intThe $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
$xis equal to$y. - a negative number means
$xis before$y. - a positive number means
$xis after$y.
Sorting 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);Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)How it works.
- First, define an array of three numbers 2, 1, and 3.
- Second, use the
usort()function to sort the$numbersarray. 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);If you use PHP 7 or newer, you can use the spaceship operator (<=>) to make the code more concise:
$x <=> $yThe 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);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);Note that PHP introduced the arrow functions since PHP 7.4.
Sorting 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);Output:
Array(3)
{
[0]=> string(4) "Alex"
[1]=> string(4) "John"
[2]=> string(5) "Peter"
}Sorting 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);Output:
Array
(
[0] => Person Object
(
[name] => Bob
[age] => 20
)
[1] => Person Object
(
[name] => Alex
[age] => 25
)
[2] => Person Object
(
[name] => Peter
[age] => 30
)
)How it works.
- First, define a
Personclass that has two properties:nameandage. - Second, define the
$grouparray that holds thePersonobjects. - Third, use the
usort()function to sort thePersonobjects of the$grouparray. Theusort()function uses a comparison function that compares the age of twoPersonobjects.
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);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);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']);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.
Thank you for your feedback!