PHP - uasort() Function
The PHP uasort() function is used to sort an associative array by its value and using user-defined comparison function. The function must return an integer to work correctly and it should take only two parameters to compare.
Syntax
uasort(array, myfunction)
Parameters
array |
Required. Specify the associative array to sort |
myfunction |
Required. Specify user-defined function to compare values. The function must return an integer to work correctly and it should take only two parameters to compare. |
Return Value
Returns TRUE on success and False in failure.
Example:
In the below example, uasort() function to used to sort an associative array called MyArray, according to the value and using user-defined function MyFunction.
<?php function MyFunction($x, $y) { if ($x == $y) return 0; return ($x < $y)? -1: 1; } $MyArray = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35); uasort($MyArray, "MyFunction"); print_r($MyArray); ?>
The output of the above code will be:
Array ( [Kim] => 22 [Marry] => 25 [John] => 30 [Adam] => 35 [Jo] => 45 )
❮ PHP Array functions