PHP 8 reference · Array Sorting Functions

PHP uksort() Function

Sort an array by key with your own comparison function, keeping values with their keys.

PHP 8 Since 4.0

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

Syntax

uksort(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

Natural, case-insensitive key orderTry it yourself
<?php
$files = ["file10.txt" => 3, "file2.txt" => 1, "File1.txt" => 7];
uksort($files, "strnatcasecmp");
print_r($files);

Output

Array
(
    [File1.txt] => 7
    [file2.txt] => 1
    [file10.txt] => 3
)
A custom key orderTry it yourself
<?php
$order = ["high" => 0, "medium" => 1, "low" => 2];
$tasks = ["low" => "tidy desk", "high" => "fix outage", "medium" => "review PR"];
uksort($tasks, fn($a, $b) => $order[$a] <=> $order[$b]);
print_r($tasks);

Output

Array
(
    [high] => fix outage
    [medium] => review PR
    [low] => tidy desk
)

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?