uksort()
Learn PHP uksort(): sort an array by its keys using a user-defined comparison callback. Covers syntax, return value, and how it differs from ksort() and usort().
Introduction
uksort() sorts an array by its keys using a comparison function you write yourself. Unlike ksort(), which only sorts keys in their natural ascending order, uksort() lets you decide the order — alphabetical, reverse, by string length, by a custom priority list, or any rule you can express in code. The key-to-value association is always preserved.
This page covers the syntax and return value, how the comparison callback works, several runnable examples (including the spaceship operator), common gotchas, and how uksort() differs from related sorting functions.
Syntax
uksort(array &$array, callable $callback): true$array— the array to sort. It is passed by reference and sorted in place, so the original variable is modified directly.$callback— a comparison function that receives two keys ($aand$b) and returns an integer:- a negative number if
$ashould come before$b, 0if they are considered equal,- a positive number if
$ashould come after$b.
- a negative number if
The function returns true (in PHP 8+; it returned a bool previously). Because the sort happens by reference, you read the result from the original array variable — not from the return value.
The callback compares keys, not values. That is the one fact that distinguishes
uksort()fromusort()(which compares values) anduasort()(which compares values but keeps key association).
Basic example: sort keys alphabetically
Suppose we have an array of fruits keyed by name, and we want them in alphabetical order by key:
<?php
$fruits = [
"orange" => 3,
"apple" => 2,
"banana" => 1,
];
function cmp($a, $b)
{
return strcmp($a, $b);
}
uksort($fruits, "cmp");
print_r($fruits);strcmp() already returns a negative, zero, or positive integer, so it plugs straight into the callback. The output is sorted by key:
Array
(
[apple] => 2
[banana] => 1
[orange] => 3
)Using the spaceship operator
Since PHP 7, the spaceship operator <=> returns -1, 0, or 1 for less-than, equal, or greater-than — exactly the shape uksort() expects. With an arrow function the callback becomes a one-liner:
<?php
$data = ["delta" => 1, "alpha" => 2, "charlie" => 3, "bravo" => 4];
uksort($data, fn($a, $b) => $a <=> $b);
print_r($data);This sorts the keys ascending:
Array
(
[alpha] => 2
[bravo] => 4
[charlie] => 3
[delta] => 1
)To reverse the order, swap the operands: fn($a, $b) => $b <=> $a.
A custom ordering
The real power of uksort() is sorting by a rule that no built-in function provides — for example, by key length, then alphabetically for ties:
<?php
$config = [
"id" => 1,
"name" => "Ann",
"is_active" => true,
"x" => 0,
];
uksort($config, function ($a, $b) {
return strlen($a) <=> strlen($b) // shortest keys first
?: strcmp($a, $b); // ties broken alphabetically
});
print_r($config);The ?: short-circuit returns the length comparison unless it is 0, in which case it falls back to the alphabetical comparison:
Array
(
[x] => 0
[id] => 1
[name] => Ann
[is_active] => 1
)Common gotchas
- It returns
true, not the sorted array. Writing$sorted = uksort($arr, ...)gives youtrue. Use$arrafterwards instead. - The original array is mutated. Copy it first (
$copy = $arr;) if you need to keep the original order. - The callback must be consistent. Returning random values (e.g.
rand(-1, 1)) gives undefined results. To shuffle, useshuffle()on values orarray_rand()on keys instead. - Return an integer. Returning a
boolworks by coercion but is fragile —falsebecomes0(equal), soreturn $a < $b;is a bug. Use<=>orstrcmp().
How uksort() compares to related functions
| Function | Sorts by | Custom callback | Keeps key association |
|---|---|---|---|
uksort() | keys | yes | yes |
ksort() | keys | no (natural order) | yes |
usort() | values | yes | no (reindexed) |
uasort() | values | yes | yes |
asort() | values | no | yes |
In short: reach for uksort() whenever you need to order an associative array by its keys with a rule that ksort() cannot express. For more on the broader topic, see Sorting Arrays in PHP.
Conclusion
uksort() sorts an associative array by its keys using a comparison callback you control, modifying the array in place and preserving key-to-value links. With the spaceship operator the callback is concise, and custom logic lets you implement orderings no built-in function offers.
Diagram
graph LR
A[Array] --> B(Function);
B --> C[Comparison result];
C --> D{Is result negative?};
D -->|Yes| E[Swap];
C -->|No| F[Do not swap];
F --> G[Next comparison];
E --> G[Next comparison];