PHP Function Reference

PHP uasort() Function



The PHP uasort() function is used to sort an array by its value 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

uasort(array, myfunction)

Parameters

array Required. Specify the input array to sort.
myfunction Required. Specify user-defined function to compare values. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, uasort() function is used to sort an array in ascending order, according to the value and using user-defined function.

<?php
//function to sort in ascending order
function MyFunc($x, $y) {
  if ($x == $y) 
     return 0;
  return ($x < $y)? -1: 1;
}

$Arr = array("Marry"=>25, 
             "John"=>30, 
             "Jo"=>45, 
             "Kim"=>22, 
             "Adam"=>35);
                 
uasort($Arr, "MyFunc");

print_r($Arr);
?>

The output of the above code will be:

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

Example:

Consider one more example where the function is defined to sort the array in descending order.

<?php
//function to sort in descending order
function MyFunc($x, $y) {
  if ($x == $y) 
    return 0;
  return ($x < $y)? 1: -1;
}

$Arr = array("Marry"=>25, 
             "John"=>30, 
             "Jo"=>45, 
             "Kim"=>22, 
             "Adam"=>35);
                 
uasort($Arr, "MyFunc");

print_r($Arr);
?>

The output of the above code will be:

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

❮ PHP Array Reference