Thursday, July 3, 2008

Associative arrays in PHP

A few days ago we studied about associative arrays in PHP. Now, you cannot sort an associative array by using the sort() function. Let’s see what happens if you apply the sort() function on an associative array in PHP:


<?php


$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";


sort($narray);


foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}


?>



The outcome you get is:


0 = Computer Associated
1 = International Business Machines
2 = Microsoft
3 = Something Random
4 = United Kingdon
5 = World Health Organization


So you can see that if you apply the sort() function on an associative array, it is sorted by the numeric value of the index. To sort an associative array, you use the asort() function in the following manner:



<?php


$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";
asort($narray);
foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}


?>



The result is:


CA = Computer Associated
IBM = International Business Machines
MS = Microsoft
BA = Something Random
UK = United Kingdon
WHO = World Health Organization


As you can see, the array has been sorted in the ascending order by the value of the array, and not the string index value, or the key of the array. You can use arsort() to sort an associative array in the descending order.


To sort an associative array according to the key of the array, you can use the ksort() function in the following manner:



<?php


$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";


ksort($narray);


foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}


?>



Similarly, you can sort an associative array according to the key, in ascending order by using the krsort() function.

No comments: