PHP Array Sorting
The elements in the array can be sorted in ascending or descending order, either in alphabetical or numerical sequence.
PHP-sorting functions for arrays
In this section, we will learn the following PHP array sorting functions:
- Sort ()-sorts an array in ascending order
- Rsort ()-sorts the array in descending order
- Asort ()-sorts associative arrays in ascending order based on values
- Ksort ()-Sorts the associative array in ascending order, based on the key
- Arsort ()-sorts associative arrays in descending order by value
- Krsort ()-Sorts the associative array in descending order, based on the key
Sorting an array in ascending order-sort ()
The following example sorts the elements of an array $cars in ascending alphabetical order:
Instance
<?php$cars=array ("Volvo", "BMW", "SAAB"); sort ($cars); >
The result of the output is the BMW
SAAB
Volvo
Sort stands for ascending
The following example sorts the elements in an array $numbers in ascending numbers:
Instance
<?php$numbers=array (3,5,1,22,11); sort ($numbers);? >
Sort is ascending
The result of the output is
1341122
Sort ascending by value of an array-asort ()
The following example sorts the associative arrays in ascending order based on values:
Instance
<?php$age=array ("Bill" = "+", "Steve" = "Notoginseng", "Peter" and "Asort"); ($age);? >
Key=bill, value=35
Key=steve, value=37
Key=peter, value=43
Sort ascending by Key array-ksort ()
The following example sorts an associative array in ascending order based on the key:
Instance
<?php$age=array ("Bill" = "+", "Steve" = "Notoginseng", "Peter" and "Ksort"); ($age);? >
Key=bill, value=35
Key=peter, value=43
Key=steve, value=37
Sort Descending by Value array-arsort ()
The following example sorts the associative arrays by value in descending order:
Instance
<?php$age=array ("Bill" = "+", "Steve" = "Notoginseng", "Peter" and "Arsort"); ($age);? >
Key=peter, value=43
Key=steve, value=37
Key=bill, value=35
Sort descending order of keys by Key-Krsort ()
The following example sorts the associative arrays in descending order based on the key:
Instance
<?php$age=array ("Bill" = "+", "Steve" = "Notoginseng", "Peter" and "Krsort"); ($age);? >
Key=steve, value=37
Key=peter, value=43
Key=bill, value=35
PHP Array Sorting