PHP uksort() Function
The uksort() function is a built-in function in PHP that sorts an associative array by its keys using a user-defined comparison function. This function works only on keys, not on values.
In the uksort() function:
- “u” stands for “user-defined”, meaning that you provide your own custom or user-defined comparison function to control the sorting.
- “k” stands for “key”, meaning that the sorting is done based on the keys of the array, not the values.
The uksort() function preserves the association between keys and values in the array during sorting. Since array is sorted in-place, therefore, the original array will be also modified.
Syntax of uksort() Function in PHP
The general syntax to define uksort() function in PHP is as follows:
uksort(array &$array, callable $callback): bool
In the syntax of uksort() function,
- $array represents the name of an associative array that has to be sorted passed by reference. This means the original array is modified directly.
- $callback is a user-defined comparison function. This function must accept two parameters, which represent two keys of the array that are being compared.
The comparison function will return:
- A negative number if the first key come before the second key.
- Zero if the two keys are equal in terms of sorting order.
- A positive number if the first key should come after the second key.
The uksort() function returns true on the successful sorting operation. Otherwise, it returns false if the sorting operation fails.
Basic Examples of PHP uksort() Function
Example 1: Let’s take a simple example in which we will sort keys of an array alphabetically (case-sensitive).
<?php
$fruits = [
'o' => 'Orange',
'a' => 'Apple',
'b' => 'Banana',
'p' => 'Pear'
];
// User-defined comparison function.
function compareKeys($a, $b) {
return strcmp($a, $b);
}
uksort($fruits, 'compareKeys');
print_r($fruits);
?>
Output: Array ( [a] => Apple [b] => Banana [o] => Orange [p] => Pear )
In this example, we have used the strcmp() function to compare key names such as o, a, b, etc. alphabetically. As a result, the array is sorted by key names in ascending order.
Example 2: Let’s write a PHP program in which we will sort key names in reverse alphabetical order using uksort() function. We will do this simply reverse the comparison.
<?php
$colors = [
'red' => '#FF0000',
'green' => '#00FF00',
'blue' => '#0000FF',
'yellow' => '#FFFF00'
];
function reverseCompare($key1, $key2) {
return strcmp($key2, $key1);
}
uksort($colors, 'reverseCompare');
print_r($colors);
?>
Output: Array ( [yellow] => #FFFF00 [red] => #FF0000 [green] => #00FF00 [blue] => #0000FF )
Advanced Examples on uksort() Function
Example 3: Let’s write a PHP program in which we will sort array key names naturally using strnatcmp() function. By default, the strcmp() function is case-sensitive and purely alphabetical.
<?php
$products = [
'Laptop' => 1200,
'mouse' => 30,
'Keyboard' =>80,
'monitor' => 250
];
function caseInsensitiveCompare($key1, $key2) {
return strcasecmp($key1, $key2);
}
uksort($products, 'caseInsensitiveCompare');
print_r($products);
?>
Output: Array ( [Keyboard] => 80 [Laptop] => 1200 [monitor] => 250 [mouse] => 30 )
Example 4: Sometimes, keys in an array can be mixed types, such as numbers and strings. Let’s write a PHP program in which we will sort key names with numbers and strings.
<?php
$mixed = [
'20' => 'twenty',
'3' => 'three',
'o' => 'orange',
'a' => 'apple',
'10' => 'ten'
];
uksort($mixed, function($key1, $key2) {
if (is_numeric($key1) && is_numeric($key2)) {
return (int)$key1 - (int)$key2;
}
return strcmp($key1, $key2);
});
print_r($mixed);
?>
Output: Array ( [3] => three [10] => ten [20] => twenty [a] => apple [o] => orange )
Sorting Key Names by Length
Example 5: Let’s write a PHP program in which we will sort key names by the length of the keys.
<?php
$animals = [
'elephant' => 'Large',
'cat' => 'Small',
'giraffe' => 'Tall',
'dog' => 'Loyal'
];
// User-defined comparison function.
function lengthCompare($key1, $key2) {
$lenA = strlen($key1);
$lenB = strlen($key2);
if ($lenA == $lenB) {
return 0;
}
return ($lenA < $lenB) ? -1 : 1;
}
uksort($animals, 'lengthCompare');
print_r($animals);
?>
Output: Array ( [cat] => Small [dog] => Loyal [giraffe] => Tall [elephant] => Large )
When Should You Use uksort() Function in PHP?
You should use uksort() function in PHP programming when:
- You need to define your user-defined comparison function to order array keys.
- Sorting array keys using standard ksort() function is not enough.
- You need complex multi-level sorting based on extracted parts of the key.
- You want natural or case-insensitive key sorting.
Comparison with Other Sorting Functions
Function | Sorts By | Maintain Key Association | Comparison Method |
---|---|---|---|
sort() | Values | No | Built-in |
asort() | Values | Yes | Built-in |
ksort() | Keys | Yes | Built-in |
usort() | Values | No | User-defined |
uksort() | Keys | Yes | User-defined |
uasort() | Values | Yes | User-defined |
uksort() | Keys | Yes | User-defined |