PHP usort() Function

The usort() function is used to sort an array by its values using a user-defined comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

TRUE on success. FALSE on failure

Parameter Description
array Required. Specifies the array to sort
myfunction Optional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

Syntax

usort(array,myfunction); 

Example

function my_sort_array($a,$b)
{
	if ($a==$b) return 0;
		return ($a<$b)?-1:1;
}

$a=array(3,2,7,5);
usort($a,"my_sort_array");

$arraylength=count($a);
for($x=0;$x<$arraylength;$x++)
{
  echo $a[$x];
  echo "
";
}

Output

2
3
5
7

Leave a Reply

Your email address will not be published. Required fields are marked *