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

uasort() function in PHP


The uasort() sorts an array with a user-defined function and maintain index association.

Syntax

uasort(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 uasort() 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("a"=>30,"b"=>12,"c"=>75);
uasort($myarr,"display");

foreach($myarr as $x=>$x_value) {
   echo "Key=" . $x . " Value=" . $x_value;
   echo "<br>";
}
?>

Output

The following is the output −

Key=b Value=12
Key=a Value=30
Key=c Value=75