PHP Array Sorting
- Previous Page PHP Arrays
- Next Page PHP Super Global
Elements in the array can be sorted in ascending or descending order by letter or number.
PHP - Array Sorting Functions
In this section, we will learn the following PHP array sorting functions:
- sort() - Sorts the array in ascending order
- rsort() - Sorts the array in descending order
- asort() - Sorts associative arrays in ascending order by value
- ksort() - Sorts associative arrays in ascending order by key
- arsort() - Sorts associative arrays in descending order by value
- krsort() - Sorts associative arrays in descending order by key
Ascending sort of the array - sort()
The following example sorts the elements of the array $cars in alphabetical order:
Example
<?php $cars=array("porsche","BMW","Volvo"); sort($cars); ?>
The following example sorts the elements of the array $numbers in ascending order by number:
Example
<?php $numbers=array(3,5,1,22,11); sort($numbers); ?>
Sort an array in descending order - rsort()
The following example sorts the elements of the array $cars in descending order by letter:
Example
<?php $cars=array("porsche","BMW","Volvo"); rsort($cars); ?>
The following example sorts the elements of the array $numbers in descending order by number:
Example
<?php $numbers=array(3,5,1,22,11); rsort($numbers); ?>
Sort an array in ascending order by value - asort()
The following example sorts an associative array in ascending order by value:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); asort($age); ?>
Sort an array in ascending order by key - ksort()
The following example sorts an associative array in ascending order by key:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); ksort($age); ?>
Sort an array in descending order by value - arsort()
The following example sorts an associative array in descending order by value:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); arsort($age); ?>
Sort an array in descending order by key - krsort()
The following example sorts an associative array in descending order by key:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); krsort($age); ?>
Complete PHP Array Reference Manual
For a complete reference manual of array functions, please visit our PHP Array Reference Manual.
This reference manual includes a brief description and usage examples for each function.
- Previous Page PHP Arrays
- Next Page PHP Super Global