Sunday, January 18, 2026
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
32474 POSTS0 COMMENTS
Milvus
118 POSTS0 COMMENTS
Nango Kala
6846 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12063 POSTS0 COMMENTS
Shaida Kate Naidoo
6985 POSTS0 COMMENTS
Ted Musemwa
7219 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6911 POSTS0 COMMENTS