Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

uasort

Sorts an array by a custom rule, keeping the keys.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array being sorted.
$callbackcallableA function comparing two elements.

Return value

trueAlways `true`; the array itself is modified.

Examples

Sorting by a nested field while keeping the keys:

<?php
 
$users = [
    'oleg' => ['age' => 31],
    'anna' => ['age' => 25],
];
 
uasort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
 
echo implode(', ', array_keys($users));

Output:

anna, oleg

Notes

usort() would replace the keys with numbers. uksort() sorts by key with a custom rule.

See also

  • usort — Sorts an array by a custom comparison rule.
  • asort — Sorts an array by value, keeping the keys.

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.