PHP Function Reference

PHP usort() Function



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

Note: This function assigns new keys to the elements in array. It removes any existing keys that may have been assigned, rather than just reordering the keys.

Syntax

usort(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, usort() function is used to sort an array in ascending order 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", "John", "Jo", "Kim", "Adam");
usort($Arr, "MyFunc");

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [0] => Adam
    [1] => Jo
    [2] => John
    [3] => Kim
    [4] => Marry
)

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", "John", "Jo", "Kim", "Adam");
usort($Arr, "MyFunc");

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [0] => Marry
    [1] => Kim
    [2] => John
    [3] => Jo
    [4] => Adam
)

❮ PHP Array Reference