3.1 KiB
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
$freecodecamp = array("free", "code", "camp");
sort($freecodecamp);
print_r($freecodecamp);
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
$freecodecamp = array("free", "code", "camp");
rsort($freecodecamp);
print_r($freecodecamp);
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
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
asort($freecodecamp);
print_r($freecodecamp);
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
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
ksort($freecodecamp);
print_r($freecodecamp);
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
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
arsort($freecodecamp);
print_r($freecodecamp);
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
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
krsort($freecodecamp);
print_r($freecodecamp);
Output:
Array
(
[zero] => free
[two] => camp
[one] => code
)