Thursday, July 3, 2008

Sorting an Array in PHP

Now and then you need to sort your arrays alphabetically or numerically, if nothing else, then just to apply some programming logic and attain the desired output. You can sort an array in PHP by using two functions: sort(), to sort an array in ascending order, and rsort(), to sort an array in the reverse order, or descending order. I’ll illustrate this function with an example.

First, we loop through an array without applying any sorting:


<?php


$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";


for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}


?>



The output of this PHP code is:


Alfred
Robert
Deepak
Teresa
Joshua
Chandni
Sadiq
Vladimir


Now we apply the sort() function and see what happens.



<?php


$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";


sort($narray);


for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}


?>



The output of this PHP code is:


Alfred
Chandni
Deepak
Joshua
Robert
Sadiq
Teresa
Vladimir


You can see that the names have been alphabetically sorted in the ascending order. To sort of the names in descending order, we change the program like this:



<?php


$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";


rsort($narray);


for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}


?>



Now the output is:


Vladimir
Teresa
Sadiq
Robert
Joshua
Deepak
Chandni
Alfred



No comments: