Home >>PHP Array Functions >PHP asort() Function
PHP asort() function is used to sort any given input array according to its values. It sorts the given array in a way that the relation between indexes and values is maintained. By default it sorts the array values in ascending order.It accepts two parameters $array and $sort type. It returns a Boolean value True on success and False on failure as result.
Syntax:
asort($array, $sorttype);
Parameter | Description |
---|---|
array | This is a required parameter. This parameter defines the array to sort. |
sorttype | This is an optional parameter. This parameter defines how to compare the array elements. |
Here is an example of asort() function in PHP:
<html> <body> <pre> <?php for($i=10;$i>=0;$i--) { $x[]=$i; } asort($x); print_r($x); ?> </pre> </body> </html>
Array ( [10] => 0 [9] => 1 [8] => 2 [7] => 3 [6] => 4 [5] => 5 [4] => 6 [3] => 7 [2] => 8 [1] => 9 [0] => 10 )
Example 2:
<html> <body> <pre> <?php for($i=10;$i>=0;$i--) { $x[]=$i; } asort($x); echo "Sorted using the asort(): <br>"; print_r($x); arsort($x); echo "Sorted using the arsort(): <br>"; print_r($x); ?> </pre> </body> </html>
Sorted using the asort(): Array ( [10] => 0 [9] => 1 [8] => 2 [7] => 3 [6] => 4 [5] => 5 [4] => 6 [3] => 7 [2] => 8 [1] => 9 [0] => 10 ) Sorted using the arsort(): Array ( [0] => 10 [1] => 9 [2] => 8 [3] => 7 [4] => 6 [5] => 5 [6] => 4 [7] => 3 [8] => 2 [9] => 1 [10] => 0 )
Example 3:
<html> <body> <pre> <?php for($i=0;$i<=15;$i++) { $x[]=$i; } asort($x,1); echo "When sorted as a Numeric Value: <br>"; print_r($x); asort($x,2); echo "When sorted as a String Value: <br>"; print_r($x); ?> </pre> </body> </html>
When sorted as a Numeric Value: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 ) When sorted as a String Value: Array ( [0] => 0 [1] => 1 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )