PHP arsort() Function
The PHP arsort() function is used to sort an array in descending order, according to the value and maintaining key to value association. This is used mainly when sorting associative arrays where the actual element order is significant.
Syntax
arsort(array, flags)
Parameters
array |
Required. Specify the associative array to sort |
flags |
Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
|
Return Value
Returns true on success and false in failure.
Exceptions
NA.
Example:
In the example below, arsort() function is used to sort an associative array in descending order, according to the value.
<?php $Arr = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35); arsort($Arr); print_r($Arr); ?>
The output of the above code will be:
Array ( [Jo] => 45 [Adam] => 35 [John] => 30 [Marry] => 25 [Kim] => 22 )
Example:
Consider one more example where this function is used to sort an associative array using case-insensitive natural ordering.
<?php $Arr = array("Red"=>"Color1", "Green"=>"color2", "Blue"=>"Color3", "White"=>"Color20"); arsort($Arr, SORT_NATURAL | SORT_FLAG_CASE); print_r($Arr); ?>
The output of the above code will be:
Array ( [White] => Color20 [Blue] => Color3 [Green] => color2 [Red] => Color1 )
❮ PHP Array Reference