PHP uasort() Function (original) (raw)

Last Updated : 20 Jun, 2023

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:

  1. array_name: This parameter represents the array which we need to sort.
  2. 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:

}
// 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
)

}
// 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: https://www.php.net/manual/en/function.uasort.php