PHP
Note: This function is most helpful in sorting Associative Arrays because it preserves the relation between keys and values.
Syntax
boolean uksort( $array, ‘function_name’);
Parameters
The PHP uksort Function expects two mandatory parameters. The description of the parameters is as follows:
- $array: The first parameter is the array you want to sort.
- function_name: The second parameter is the name of the function you want to use to sort the array. The comparison function should return an integer value. If both the elements are equal, it should returns 0. If the first parameter is greater than the second, it should return 1 and otherwise -1.
Caution: If you return non integer values from the comparison function, they will be cast to integer values. Hence, values such as 0.9 or 0.1 will both cast to integer value 0.
Return Value
The PHP
Examples
Let’s discuss a few examples of using the PHP uksort.
Example 1: Simple Comparison Function
For instance, consider an integer array and a simple comparison function.
<?php function compare($a, $b) { if ($a == $b) { return 0; } else if ($a > $b) { return 1; } else { return -1; } } $testArray = array(1 => 4, 0 => 2, 3 => 1, 2 => 5, 4 => 3); uksort($testArray, 'compare'); /* Array ( [0] => 2 [1] => 4 [2] => 5 [3] => 1 [4] => 3 ) */ ?>
In the above example, the comparison function will return an integer value according to the parameters. The function sorts the arrays according to the keys. Also, you can note that it preserves the original keys of the input array.
Example 2: Associative Array
Similarly, you can sort an associative array on keys using the uksort function. In the below example, we sort the array containing strings using PHP strcmp Function.
<?php function compare($a, $b) { return strcmp($a, $b); } $testArray = array('a' => 'apple', 'c' => 'cat', 'd' => 'dog', 'b' => 'ball'); uksort($testArray, 'compare');print_r($testArray); /* Array ( [a] => apple [b] => ball [c] => cat [d] => dog ) */ ?>
Conclusion
In this article, we discussed the PHP uksort Function. It sorts an array

Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.