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
Syntax
uksort(array &$array, callable $callback): true
Parameters
| Parameter | Description |
|---|---|
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
<?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
)<?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
Related
usort()· Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons.uasort()· Sort an array by value with your own comparison function, keeping keys attached to their values.ksort()· Sort an array by key in ascending order, keeping each value with its key.- PHP Arrays · tutorial
- PHP Array Functions · tutorial