PHP uasort() Function

The uasort() function is a builtin function in PHP and is used to sort an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.
Syntax:
boolean uasort(array_name, user_defined_function);
Parameter: This function accepts two parameters and are described below:
- array_name: This parameter represents the array which we need to sort.
- user_defined_function: This is a comparator function and is used to compare values and sort the array. This function returns three types of values described below:
- It return 0 when a=b
- It return 1 when a>b and we want to sort input array in ascending order otherwise it will return -1 if we want to sort input array in descending order.
- It return -1 when a<b and we want to sort input array in ascending order otherwise it will return 1 if we want to sort input array in descending order.
Return Value: It returns a boolean value, i.e. either TRUE on success and FALSE on failure.
Examples:
Input: array
(
"a" => 4,
"b" => 2,
"g" => 8,
"d" => 6,
"e" => 1,
"f" => 9
)
Output: Array
(
[e] => 1
[b] => 2
[a] => 4
[d] => 6
[g] => 8
[f] => 9
)
Below programs illustrates the uasort() function in PHP:
-
Sorting in ascending order: To sort the input array in ascending order, in the comparator function we will return 1 when a>b or -1 when a<b. Below program illustrates this:
<?php// PHP program to sort in ascending// order using uasort() functionÂÂ// user_defined comparator functionfunctionsorting($a,$b){   Âif($a==$b)return0;       Âreturn($a<$b)?-1:1;}ÂÂ// input array Â$arr=array("a"=>4,"b"=>2,"g"=>8,"d"=>6,"e"=>1,"f"=>9);ÂÂuasort($arr,"sorting");ÂÂ// printing sorted array.print_r($arr);ÂÂ?>Output:
Array ( [e] => 1 [b] => 2 [a] => 4 [d] => 6 [g] => 8 [f] => 9 ) -
Sorting in descending order: To sort the input array in descending order, in the comparator function we will return -1 when a>b or 1 when a<b. Below program illustrates this:
<?php// PHP program to sort in descending// order using uasort() functionÂÂ// user_defined comparator functionfunctionsorting($a,$b)Â{Â Â Â Âif($a==$b)return0;Â Â Â Â Â Â Â Âreturn($a>$b) ? -1 : 1;}ÂÂ// input array$input=array("d"=>"R","a"=>"G","b"=>"X","f"=>"Z");ÂÂuasort($input,"sorting");ÂÂ// printing sorted array.print_r($input);ÂÂ?>Output:
Array ( [f] => Z [b] => X [d] => R [a] => G )
Reference:
http://php.net/manual/en/function.uasort.php



