PHP provides a number of predefined functions to sort an array.
sort() , rsort()
: For sorting an indexed arrays by valuesasort() , arsort()
: For sorting an associative arrays by valueksort() , krsort()
: For sorting an associative arrays by keyThe sort()
function is used for sorting the elements of the indexed array in ascending order by values. Elements will be arranged from lowest to highest.
<?php $colors = array("red", "orange", "blue", "green"); sort($colors); var_dump($colors); // array("blue", "green", "orange", "red"); $colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green"); sort($colors); var_dump($colors); // array(0=>"blue", 1=>"green", 2=>"orange", 3=>"red"); $colors = array("red", "#333", "blue", "green"); sort($colors); var_dump($colors); // array("#333", "blue", "green", "red"); ?>
The rsort()
function is used to sort an array in reverse order by values.
<?php $colors = array("red", "orange", "blue", "green"); rsort($colors); var_dump($colors); // array("red", "orange", "green", "blue"); ?>
The asort()
function is used to sort an associative array in ascending order according to it's value.
The main difference from sort()
function is that asort()
would maintain index association.
<?php $colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green"); sort($colors); var_dump($colors); // array(0=>"blue", 1=>"green", 2=>"orange", 3=>"red"); $colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green"); asort($colors); var_dump($colors); // array(4=>"blue", 2=>"green", 3=>"orange", 1=>"red"); ?>
The function arsort()
is like asort()
but sort the array in reverse order.
<?php $colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green"); arsort($colors); var_dump($colors); // array(1=>"red", 3=>"orange", 2=>"green", 4=>"blue"); ?>
The ksort()
function is similar to asort()
but it sort the array according to it's key.
<?php $colors = array(1=>"red", 5=>"orange", 4=>"blue", 2=>"green"); ksort($colors); var_dump($colors); // array(1=>"red", 2=>"green", 4=>"blue", 5=>"orange"); ?>
The function krsort()
is like ksort()
but sort the array in reverse order.
<?php $colors = array(1=>"red", 5=>"orange", 4=>"blue", 2=>"green"); krsort($colors); var_dump($colors); // array(5=>"orange", 4=>"blue", 2=>"green", 1=>"red"); ?>