PHP 8 reference · Array Sorting Functions

PHP usort() Function

Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

usort(array &$array, callable $callback): true

Parameters

ParameterDescription
array The array to sort (changed in place).
callback fn($a, $b) returns a negative number, 0 or a positive number; $a <=> $b does this for you.

Return value

Always true.

Examples

Sort records by a fieldTry it yourself
<?php
$people = [["name" => "Ada", "age" => 36], ["name" => "Alan", "age" => 41], ["name" => "Grace", "age" => 29]];
usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
echo implode(", ", array_column($people, "name")), "\n";

Output

Grace, Ada, Alan
Sort by length, then alphabeticallyTry it yourself
<?php
$words = ["banana", "kiwi", "apple", "fig"];
usort($words, fn($a, $b) => [strlen($a), $a] <=> [strlen($b), $b]);
echo implode(", ", $words), "\n";

Output

fig, kiwi, apple, banana
Descending and stableTry it yourself
<?php
$items = [["n" => "b", "p" => 2], ["n" => "a", "p" => 1], ["n" => "c", "p" => 2]];
usort($items, fn($x, $y) => $y["p"] <=> $x["p"]); // descending: swap the sides
echo implode(",", array_column($items, "n")), "\n";   // ties keep their order

Output

b,c,a

Common mistakes

  • The callback must return a number, not a boolean: fn($a, $b) => $a > $b gives wrong results. Use $a <=> $b.
  • For descending order swap the operands: $b <=> $a.

Version history

VersionChange
PHP 4.0Added
PHP 8.0Sorting is stable: elements that compare equal keep their original order.
PHP 8.2The return type is true (it was bool).

In other languages

Was this page helpful?