PHP - Sorting Arrays
In PHP, there are built-in functions which can be used to sort arrays. In this section, we will discuss PHP sort functions:
- sort(): Sort an indexed array in ascending order.
- rsort(): Sort an indexed array in descending order.
- asort(): Sort an associative array in ascending order, according to the value.
- arsort(): Sort an associative array in descending order, according to the value.
- ksort(): Sort an associative array in ascending order, according to the key.
- krsort(): Sort an associative array in descending order, according to the key.
Sort Array in Ascending Order - sort()
In the below example, sort() function is used to sort the indexed array MyArray in ascending order.
<?php $MyArray = array("Marry", "John", "Kim", "Adam"); sort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [0] => Adam [1] => John [2] => Kim [3] => Marry )
Sort Array in Descending Order - rsort()
In the below example, rsort() function is used to sort the indexed array MyArray in descending order.
<?php $MyArray = array("Marry", "John", "Kim", "Adam"); rsort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [0] => Marry [1] => Kim [2] => John [3] => Adam )
Sort Array in Ascending Order by Value - asort()
In the below example, asort() function is used to sort the associative array MyArray in ascending order, according to its value.
<?php $MyArray = array("Marry"=>25, "John"=>30, "Kim"=>22, "Adam"=>35); asort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [Kim] => 22 [Marry] => 25 [John] => 30 [Adam] => 35 )
Sort Array in Descending Order by Value - arsort()
In the below example, arsort() function is used to sort the associative array MyArray in descending order, according to its value.
<?php $MyArray = array("Marry"=>25, "John"=>30, "Kim"=>22, "Adam"=>35); arsort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [Adam] => 35 [John] => 30 [Marry] => 25 [Kim] => 22 )
Sort Array in Ascending Order by Key - ksort()
In the below example, ksort() function is used to sort the associative array MyArray in ascending order, according to its key.
<?php $MyArray = array("Marry"=>25, "John"=>30, "Kim"=>22, "Adam"=>35); ksort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [Adam] => 35 [John] => 30 [Kim] => 22 [Marry] => 25 )
Sort Array in Descending Order by Key - krsort()
In the below example, krsort() function is used to sort the associative array MyArray in descending order, according to its key.
<?php $MyArray = array("Marry"=>25, "John"=>30, "Kim"=>22, "Adam"=>35); krsort($MyArray); print_r($MyArray); ?>
The output of the above code will be:
Array ( [Marry] => 25 [Kim] => 22 [John] => 30 [Adam] => 35 )