PHP uksort() Function (original) (raw)

Last Updated : 23 Sep, 2024

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 which are described below:

  1. ****$array**: This parameter specifies an array that we need to sort.
  2. **myFunction: This parameter specifies the name of a user-defined function that will be used to sort the keys of array _$array. This comparison function must return an integer.

**Return value:

Examples of uksort() Function

**Example 1: Using uksort() Function with a Custom Key Comparison Function

In this example, the uksort() function is used to sort the array based on the keys using a user-defined comparison function that sorts the keys in descending order.

PHP `

$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 )

**Example 2: Using uksort() with Ascending Key Comparison

In this example, the uksort() function is used with a custom comparison function to sort the keys in ascending order.

PHP `

$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.