Home >>PHP Array Functions >PHP uasort() Function
PHP uasort() function is used to sort the given input array such that the array indexes maintain their relation with their associated array elements using a user-defined function. It accepts two parameters $array and the user defined function name. It returns a boolean value TRUE on success and FALSE on failure as result.
Syntax:
uasort($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 compar ison function. |
Here is an example of uasort() function in PHP:
<html> <body> <?php function compare($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } $arr=array("a"=>1,"b"=>2,"c"=>10,"d"=>66,"e"=>5); uasort($arr,"compare"); foreach($arr as $x=>$value) { echo "Key =" . $x . ", Value =" . $value; 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("a"=>1,"b"=>2,"c"=>10,"d"=>66,"e"=>5,"f"=>25,"g"=>31); uasort($arr,"compare"); print_r($arr); ?> </pre> </body> </html>
Array ( [a] => 1 [b] => 2 [e] => 5 [c] => 10 [f] => 25 [g] => 31 [d] => 66 )