PHP Sorting Arrays
Sorting means arrange values in ascending or descending order. In this tutorial, we ll learn how to sort an array.
Functions For Sort Arrays
- sort() – sort arrays in ascending order
- rsort() – sort arrays in descending order
- asort() – sort associative arrays in ascending order, according to the value
- ksort() – sort associative arrays in ascending order, according to the key
- arsort() – sort associative arrays in descending order, according to the value
- krsort() – sort associative arrays in descending order, according to the key
1. sort() – Sort Array in Ascending Order
The following example sorts the elements of the $cities array in ascending alphabetical order:
Example
<?php $cities = array("Noida", "Jaipur", "Delhi"); sort($cars); print_r($cars); ?> |
OutPut
Array ( [0] => Delhi [1] => Jaipur [2] => Noida)
2. rsort() – Sort Array in descending Order
The following example sorts the elements of the $cities array in ascending descending order:
Example
<?php $cities = array("Noida", "Jaipur", "Delhi"); sort($cars); print_r($cars); ?> |
OutPut
Array ( [0] => Noida [1] => Jaipur [2] => Delhi)
3. asort() – sort associative arrays in ascending order, according to the value
The following example sorts the elements of the $cities array in ascending descending order:
Example
<?php // Define array $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35); // Sorting array by value and print asort($age); print_r($age); ?> |
OutPut
Array ( [0] => Noida [1] => Jaipur [2] => Delhi)
4. ksort() – sort associative arrays in ascending order, according to the value
The following example sorts the elements of the $cities array in ascending descending order:
Example
<?php // Define array $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35); // Sorting array by value and print asort($age); print_r($age); ?> |
OutPut
Array ( [0] => Noida [1] => Jaipur [2] => Delhi)
5. arsort – sort associative arrays in ascending order, according to the value
The following example sorts the elements of the $cities array in ascending descending order:
Example
<?php // Define array $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35); // Sorting array by value and print asort($age); print_r($age); ?> |
OutPut
Array ( [0] => Noida [1] => Jaipur [2] => Delhi)
6. ksort() – sort associative arrays in ascending order, according to the value
The following example sorts the elements of the $cities array in ascending descending order:
Example
<?php // Define array $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35); // Sorting array by value and print asort($age); print_r($age); ?> |
OutPut
Array ( [0] => Noida [1] => Jaipur [2] => Delhi)