Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


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

Syntax

usort(array, myfunction)

Parameters

array Required. Specify the indexed 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.

Example:

In the below example, usort() function to used to sort an indexed array called MyArray using user-defined function MyFunction.

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

  $MyArray = array("Marry", "John", "Jo", "Kim", "Adam");
  usort($MyArray, "MyFunction");

  print_r($MyArray);
?>

The output of the above code will be:

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

❮ PHP Array functions