Published by: Sujan
Published date: 16 Jun 2021
PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we'll explore some of these functions most commonly used for sorting arrays.
The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).
This print_r() statement gives the following output:
Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )
Similarly you can sort the numeric elements of the array in ascending order.
This print_r() statement gives the following output:
Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )
The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).
This print_r() statement gives the following output:
Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
The asort() function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and their values while sorting.
This print_r() statement gives the following output:
Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )
The arsort() function sorts the elements of an associative array in descending order according to the value. It works just like rsort(), but it preserves the association between keys and its values while sorting.
This print_r() statement gives the following output:
Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )
The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting, same as asort() function.
This print_r() statement gives the following output:
Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 )
The krsort() function sorts the elements of an associative array in descending order by their keys. It preserves the association between keys and its values while sorting, same as arsort() function.
This print_r() statement gives the following output:
Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )