PHP uksort() Function
The PHP uksort() function is used to sort an array by its key and using user-defined comparison function. The function must return an integer to work correctly and it should take only two parameters to compare.
Syntax
uksort(array, myfunction)
Parameters
array |
Required. Specify the input array to sort. |
myfunction |
Required. Specify user-defined function to compare keys. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument. |
Return Value
Returns true on success and false in failure.
Exceptions
NA.
Example:
In the example below, uksort() function is used to sort an array in ascending order, according to the key and using user-defined function.
<?php //function to sort in ascending order function MyFunc($x, $y) { if ($x == $y) return 0; return ($x < $y)? -1: 1; } $Arr = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35); uksort($Arr, "MyFunc"); print_r($Arr); ?>
The output of the above code will be:
Array ( [Adam] => 35 [Jo] => 45 [John] => 30 [Kim] => 22 [Marry] => 25 )
Example:
Consider one more example where the function is defined to sort the array in descending order.
<?php //function to sort in descending order function MyFunc($x, $y) { if ($x == $y) return 0; return ($x < $y)? 1: -1; } $Arr = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35); uksort($Arr, "MyFunc"); print_r($Arr); ?>
The output of the above code will be:
Array ( [Marry] => 25 [Kim] => 22 [John] => 30 [Jo] => 45 [Adam] => 35 )
❮ PHP Array Reference