PHP uasort() Function

The uasort() function sorts an array by values using a user-defined comparison function.

TRUE on success. FALSE on failure

Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.

ParameterDescription
arrayRequired. Specifies the array to sort
myfunctionOptional. 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

uasort(array,myfunction); 

Example

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

$array=array("a"=>3,"b"=>2,"c"=>7,"d"=>"5");
uasort($array,"my_sort");
 
foreach($array as $x=>$x_value)
{
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "
";
}

Output

Key=b, Value=2
Key=a, Value=3
Key=d, Value=5
Key=c, Value=7

Leave a Reply

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