Wednesday, November 19, 2025
HomeLanguagesPHP uksort() Function

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:




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

RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6775 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6903 POSTS0 COMMENTS
Ted Musemwa
7159 POSTS0 COMMENTS
Thapelo Manthata
6858 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS