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:



  1. $array: This parameter specifies an array which we need to sort.
  2. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


Output:

Array
(
    [60] => vbscript
    [40] => jsp
    [20] => php
    [10] => javascript
)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


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



My Personal Notes arrow_drop_up

Contented with little yet wishing for more

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.