Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

usort

Sorts an array by a custom comparison rule.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array being sorted.
$callbackcallableA function comparing two elements: returns a negative number, zero or a positive one.

Return value

trueAlways `true`; the array itself is modified.

Examples

Sorting by a field:

<?php
 
$users = [['name' => 'Oleg', 'age' => 31], ['name' => 'Anna', 'age' => 25]];
 
usort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
 
echo implode(', ', array_column($users, 'name'));

Output:

Anna, Oleg

Descending order — the arguments are swapped:

<?php
 
$numbers = [3, 10, 1];
 
usort($numbers, fn ($a, $b) => $b <=> $a);
 
echo implode(', ', $numbers);

Output:

10, 3, 1

Notes

The keys are replaced with numbers from zero. To keep the keys, use uasort().

See also

  • sort — Sorts an array in ascending order.
  • asort — Sorts an array by value, keeping the keys.
  • array_map — Applies a function to every element of an array.

Related recipes

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.