Custom Array Sorting in PHP with usort
Sorting arrays in PHP is a common task, but standard sorting
functions like sort() or asort() are often
insufficient for complex data structures. This article explains how to
use PHP’s usort() function to perform custom array sorting
using user-defined comparison functions. You will learn the syntax of
usort(), how the spaceship operator
(<=>) simplifies comparison logic, and how to apply
these concepts to sort multidimensional arrays and objects.
Understanding the usort() Function
The usort() function sorts an array by its values using
a user-defined comparison function. It modifies the original array
directly (sorting in-place) and assigns new numeric keys to the
elements, discarding any existing keys.
The syntax for usort() is:
usort(array &$array, callable $callback): boolThe callback function must accept two parameters (commonly referred
to as $a and $b) and return an integer: *
Less than 0 (usually -1) if
$a should come before $b. * Greater
than 0 (usually 1) if $a should come
after $b. * Zero (0) if
$a and $b are considered equal.
Using the Spaceship Operator (<=>)
Introduced in PHP 7, the spaceship operator (<=>)
is the most efficient way to write comparison callbacks. It
automatically returns -1, 0, or 1
based on the comparison of two values.
$a <=> $breturns-1if$a < $b$a <=> $breturns0if$a == $b$a <=> $breturns1if$a > $b
Example 1: Sorting a Simple Array by String Length
In this example, we sort an array of strings from shortest to longest.
<?php
$languages = ["JavaScript", "PHP", "Python", "C", "Go"];
usort($languages, function($a, $b) {
return strlen($a) <=> strlen($b);
});
print_r($languages);
?>Output:
Array
(
[0] => C
[1] => Go
[2] => PHP
[3] => Python
[4] => JavaScript
)
To sort in descending order (longest to shortest), simply swap the
variables in the comparison:
strlen($b) <=> strlen($a).
Example 2: Sorting an Array of Associative Arrays
A common real-world scenario is sorting a list of database records or API results. Here, we sort an array of users by their age in ascending order.
<?php
$users = [
["name" => "Alice", "age" => 34],
["name" => "Bob", "age" => 22],
["name" => "Charlie", "age" => 28]
];
// Using an arrow function (PHP 7.4+) for cleaner syntax
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
print_r($users);
?>Output:
Array
(
[0] => Array ([name] => Bob, [age] => 22)
[1] => Array ([name] => Charlie, [age] => 28)
[2] => Array ([name] => Alice, [age] => 34)
)
Example 3: Sorting Objects
usort() works identically when sorting arrays of
objects. Instead of array keys, you access the object properties.
<?php
class Product {
public string $name;
public float $price;
public function __construct(string $name, float $price) {
$this->name = $name;
$this->price = $price;
}
}
$products = [
new Product("Laptop", 999.99),
new Product("Mouse", 25.50),
new Product("Keyboard", 75.00)
];
// Sort products by price, cheapest to most expensive
usort($products, fn($a, $b) => $a->price <=> $b->price);
print_r($products);
?>