Computer >> Computer tutorials >  >> Programming >> PHP

usort() function in PHP


The usort() function sorts an array by values using a user-defined function

Syntax

usort(arr, custom_function)

Parameters

  • arr − The specified array.

  • custom_function − The comparison function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return

The usort() function returns TRUE on success and FALSE on failure.

Example

The following is an example −

<?php
function display($x,$y) {
   if ($x==$y) return 0;
   return ($x<$y)?-1:1;
}
$myarr = array(39, 23, 78, 55, 99, 120);
usort($myarr,"display");

for($i=0;$x<count($myarr);$i++) {
   echo $myarr[$i];
   echo "<br>";
}
?>

Output

The following is the output −

23
39
55
78
99
120