PHP - Array Sorting Functions
PHP can put array items in order, either alphabetically or by number, and in either direction: ascending (low to high) or descending (high to low).
Six functions cover the usual cases:
sort()- orders an indexed array from low to highrsort()- orders an indexed array from high to lowasort()- orders an associative array from low to high by valueksort()- orders an associative array from low to high by keyarsort()- orders an associative array from high to low by valuekrsort()- orders an associative array from high to low by key
PHP sort() - Sort Array in Ascending Order
Call sort() on an indexed array to arrange its items in ascending order.
Sort strings in ascending order
Put the names in $cars in alphabetical order, A to Z:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
print_r($cars);
?>
Sort numbers in ascending order
Put the values in $numbers in order, smallest first:
Output: PHP script
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
print_r($numbers);
?>
PHP rsort() - Sort Array in Descending Order
rsort() does the opposite, arranging an indexed array in descending order.
Sort strings in descending order
Put the names in $cars in reverse alphabetical order, Z to A:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
print_r($cars);
?>
Sort numbers in descending order
Put the values in $numbers in order, largest first:
Output: PHP script
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
print_r($numbers);
?>
PHP asort() and arsort() - Sort Associative Array (value)
asort() orders an associative array by its values, lowest first, and each key stays attached to its value.
Sort associative array ascending by value
Order the $age array from the youngest person to the oldest:
Output: PHP script
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
print_r($age);
?>
Sort associative array descending by value
arsort() goes the other way and orders by value from highest to lowest, as this oldest-first list shows:
Output: PHP script
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
print_r($age);
?>
PHP ksort() and krsort() - Sort Associative Array (key)
To order by the keys rather than the values, use ksort(), which arranges an associative array by key, ascending.
Sort associative array ascending by key
Order the $age array alphabetically by name:
Output: PHP script
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
print_r($age);
?>
Sort associative array descending by key
krsort() reverses that, ordering by key in descending order, so the names run from Z to A:
Output: PHP script
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
print_r($age);
?>