PHP Sorting Arrays
PHP - Array Sorting Functions
The items in an array can be sorted in alphabetical or numerical order, descending or ascending.
Here are the main PHP array sorting functions:
sort()- sorts an indexed array in ascending orderrsort()- sorts an indexed array in descending orderasort()- sorts an associative array in ascending order, according to the valueksort()- sorts an associative array in ascending order, according to the keyarsort()- sorts an associative array in descending order, according to the valuekrsort()- sorts an associative array in descending order, according to the key
PHP sort() - Sort Array in Ascending Order
The sort() function sorts
an indexed array in ascending order.
Example
Sort the elements of the $cars array in ascending alphabetical order:
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
print_r($cars);
Try it Yourself »
Example
Sort the elements of the $numbers array in ascending numerical order:
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
print_r($numbers);
Try it Yourself »
PHP rsort() - Sort Array in Descending Order
The rsort() function
sorts an indexed array in descending order.
Example
Sort the elements of the $cars array in descending alphabetical order:
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
print_r($cars);
Try it Yourself »
Example
Sort the elements of the $numbers array in descending numerical order:
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
print_r($numbers);
Try it Yourself »
PHP asort() and arsort() - Sort Associative Array (value)
The asort() function sorts
an associative array in ascending order, according to the value.
Example
Sort an associative array in ascending order, according to the value:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
print_r($age);
Try it Yourself »
The arsort() function sorts
an associative array in descending order, according to the value.
Example
Sort an associative array in descending order, according to the value:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
print_r($age);
Try it Yourself »
PHP ksort() and krsort() - Sort Associative Array (key)
The ksort() function sorts
an associative array in ascending order, according to the key.
Example
Sort an associative array in ascending order, according to the key:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
print_r($age);
Try it Yourself »
The krsort() function sorts
an associative array in descending order, according to the key.
Example
Sort an associative array in descending order, according to the key:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
print_r($age);
Try it Yourself »
Complete PHP Array Reference
For a complete reference of all array functions, go to our PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!