PHP Tutorial PHP Advanced PHP Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

PHP - Array uksort() Function



The PHP Array uksort() function is used to sort an associative array by its key and using user-defined comparison function. The function must return an integer to work correctly and it should take only two parameters to compare.

Syntax

uksort(array, myfunction)

Parameters

array Required. Specify the associative array to sort
myfunction Required. Specify user-defined function to compare keys. The function must return an integer to work correctly and it should take only two parameters to compare.

Return Value

Returns TRUE on success and False in failure.

Exceptions

NA.

Example:

In the example below, uksort() function is used to sort an associative array called MyArray, according to the key and using user-defined function MyFunction.

<?php
function MyFunction($x, $y) {
  if ($x == $y) 
    return 0;
  return ($x < $y)? -1: 1;
}

$MyArray = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35);
uksort($MyArray, "MyFunction");

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [Adam] => 35
    [Jo] => 45
    [John] => 30
    [Kim] => 22
    [Marry] => 25
)

❮ PHP Array functions

5