PHP Sorting Arrays


title: Sorting Arrays

Sorting Arrays

PHP offers several functions to sort arrays. This page describes the different functions and includes examples.

sort()

The sort() function sorts the values of an array in ascending alphabetical/numerical order (E.g. A, B, C, D, E… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("free", "code", "camp"); sort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [0] => camp [1] => code [2] => free )

rsort()

The rsort() functions sort the values of an array in descending alphabetical/numerical order (E.g. Z, Y, X, W, V… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("free", "code", "camp"); rsort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [0] => free [1] => code [2] => camp )

asort()

The asort() function sorts an associative array, by it’s values, in ascending alphabetical/numerical order (E.g. A, B, C, D, E… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("zero"=>"free", "one"=>"code", "two"=>"camp"); asort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [two] => camp [one] => code [zero] => free )

ksort()

The ksort() function sorts an associative array, by it’s keys, in ascending alphabetical/numerical order (E.g. A, B, C, D, E… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("zero"=>"free", "one"=>"code", "two"=>"camp"); ksort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [one] => code [two] => camp [zero] => free )

arsort()

The arsort() function sorts an associative array, by it’s values, in descending alphabetical/numerical order (E.g. Z, Y, X, W, V… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("zero"=>"free", "one"=>"code", "two"=>"camp"); arsort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [zero] => free [one] => code [two] => camp )

krsort()

The krsort() function sorts an associative array, by it’s keys in descending alphabetical/numerical order (E.g. Z, Y, X, W, V… 5, 4, 3, 2, 1…)

<?php $Codevarsity = array("zero"=>"free", "one"=>"code", "two"=>"camp"); krsort($Codevarsity); print_r($Codevarsity);

Output:

Array ( [zero] => free [two] => camp [one] => code )

More Information:

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.