PHP 8 reference · Array Sorting Functions

PHP uasort() Function

Sort an array by value with your own comparison function, keeping keys attached to their values.

PHP 8 Since 4.0

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

Syntax

uasort(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, keep their IDsTry it yourself
<?php
$users = [
    "u7" => ["name" => "Alan", "age" => 41],
    "u3" => ["name" => "Ada", "age" => 36],
];
uasort($users, fn($a, $b) => $a["age"] <=> $b["age"]);
print_r(array_keys($users));

Output

Array
(
    [0] => u3
    [1] => u7
)
Newest firstTry it yourself
<?php
$files = ["a.txt" => "2026-03-01", "b.txt" => "2025-12-24", "c.txt" => "2026-01-15"];
uasort($files, fn($x, $y) => strcmp($y, $x)); // newest first
print_r($files);

Output

Array
(
    [a.txt] => 2026-03-01
    [c.txt] => 2026-01-15
    [b.txt] => 2025-12-24
)

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).

Was this page helpful?