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
Syntax
usort(array &$array, callable $callback): true
Parameters
| Parameter | Description |
|---|---|
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
<?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
<?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
<?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 > $bgives wrong results. Use$a <=> $b. - For descending order swap the operands:
$b <=> $a.
Version history
In other languages
sorted()· Pythonarray.sort()· JavaScript
Related
uasort()· Sort an array by value with your own comparison function, keeping keys attached to their values.uksort()· Sort an array by key with your own comparison function, keeping values with their keys.sort()· Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0.array_multisort()· Sort several arrays at once, or a table by several columns, keeping rows lined up. Changes the arrays in place.- PHP Arrays · tutorial
- PHP Array Functions · tutorial