PHP asort() Function
The PHP asort() function is used to sort an array in ascending 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
asort(array, flags)
Parameters
array |
Required. Specify the 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, asort() function is used to sort an associative array in ascending order, according to the value.
<?php $Arr = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35); asort($Arr); print_r($Arr); ?>
The output of the above code will be:
Array ( [Kim] => 22 [Marry] => 25 [John] => 30 [Adam] => 35 [Jo] => 45 )
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"); asort($Arr, SORT_NATURAL | SORT_FLAG_CASE); print_r($Arr); ?>
The output of the above code will be:
Array ( [Red] => Color1 [Green] => color2 [Blue] => Color3 [White] => Color20 )
❮ PHP Array Reference