Sorting Arrays in PHP

PHP provides various methods for sorting arrays:sort(), asort(), rsort(), arsort() and ksort(). we will discuss each function one by one.

sort() function

This is commonly used function for sorting arrays. It can be used as :

sort(array_name)

this function sort the array into alphabetical order and then rebuild the index numbers. suppose you have an array like this:

$Capitals[0] = "New Delhi";
$Capitals[2] = "Washington";
$Capitals[1] = "Landon";
$Capitals[5] = "Paris";
$Capitals[4] = "Moscow";
$Capitals[3] = "Tokyo";

you can sort above array as follows:
sort($Capitals);
After sort array will be :

$Capitals[0] = "Landon";
$Capitals[1] = "Moscow";
$Capitals[2] = "New Delhi";
$Capitals[3] = "Paris";
$Capitals[4] = "Tokyo";
$Capitals[5] = "Washington";

asort() function

asort() will also sort the array by its values in alphabetical order, but it will preserve the key
see the following example:

asort($Capitals);

The order would be:

$Capitals[1] = "Landon";
$Capitals[4] = "Moscow";
$Capitals[0] = "New Delhi";
$Capitals[5] = "Paris";
$Capitals[3] = "Tokyo";
$Capitals[2] = "Washington";

rsort() and arsort() function

Both function rsort() and arsort() work in a similar way to sort and asort. The only difference is that they return contents of an array in reverse alphabetical order.

ksort() function

The ksort() function sorts an array by the keys. The values keep their original keys.
See the following array:

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);

The order would be:

$fruits[a] = orange
$fruits[b] = banana
$fruits[c] = apple
$fruits[d] = lemon