PHP uksort() Function

The uksort() function is a built-in function in PHP and is used to sort an array according to the keys and not values using a user-defined comparison function.
Syntax:
boolean uksort($array, myFunction);
Parameter: This function accepts two parameters and are described below:
- $array: This parameter specifies an array which we need to sort.
- myFunction: This parameter specifies name of a user-defined function which will be used to sort the keys of array $array. This comparison function must return an integer.
Return value: This function returns a boolean value. It returns TRUE on success or FALSE on failure.
Below programs illustrate the uksort() function in PHP:
Program 1:
<?php // user-defined comparison function function my_sort($x, $y) { if ($x == $y) return 0; return ($x > $y) ? -1 : 1; } // Input array $names = array( "10" => "javascript", "20" => "php", "60" => "vbscript", "40" => "jsp" ); uksort($names, "my_sort"); // printing sorted array print_r ($names); ?> |
Output:
Array
(
[60] => vbscript
[40] => jsp
[20] => php
[10] => javascript
)
Program 2:
<?php // user-defined comparison function function my_sort($x, $y) { if ($x == $y) return 0; return ($x > $y) ? 1 : -1; } // Input array $names = array( "10" => "javascript", "20" => "php", "60" => "vbscript", "40" => "jsp" ); uksort($names, "my_sort"); // printing sorted array print_r ($names); ?> |
Output:
Array
(
[10] => javascript
[20] => php
[40] => jsp
[60] => vbscript
)
Note: If two values are compared as equal according to the user-defined comparison function then their order in the output array will be undefined.
Reference:
http://php.net/manual/en/function.uksort.php



