Home >>PHP Array Functions >PHP usort() Function
PHP usort() function is used to sort any given input array using the user-defined comparison function. It assigns a new integral key starting from zero to the number of elements present in the array and the old keys are lost. It returns a boolean type value TRUE in case of success and FALSE on failure.
Syntax:
usort($array, function);
Parameter | Description |
---|---|
array | This is a required parameter. It defines the array to sort. |
function | This is an optional parameter. It defines the callable comparison function. |
Here is an example of usort() function in PHP:
<html> <body> <?php function compare($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } $arr=array(62,4,2,41,8,15,6,25); usort($arr,"compare"); $length=count($arr); for($x=0;$x<$length;$x++) { echo $arr[$x]; echo "<br>"; } ?> </body> </html>
Example 2:
<html> <body> <pre> <?php function compare($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } $arr=array(62,4,2,41,8,15,6,25); usort($arr,"compare"); print_r($arr); ?> </pre> </body> </html>
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 15 [5] => 25 [6] => 41 [7] => 62 )