Sorting Arrays

chinmay.sahoo

New member
One of the most useful features of arrays is that PHP can sort them for you. PHP originally stores array elements in the order in which you create them.If you display the entire array without changing the order, the elements are displayed in the order in which they were created. Often, you want to change this order. For example, you may want to display the array in alphabetical order by value or by key.




PHP can sort arrays in a variety of ways. To sort an array that has numbers as keys, use a sort statement as follows

sort($arrayname);

This statement sorts arrays by the values and assigns new keys that are the appropriate numbers. The values are sorted with numbers first, uppercase letters next, and lowercase letters last. For example, consider the $streets
array:

$streets[0] = “Elm St.”;
$streets[1] = “Oak Dr.”;
$streets[2] = “7th Ave.”;

You enter the following sort statement:
sort($streets);

Now the array becomes as follows:

$streets[0] = “7th Ave.”;
$streets[1] = “Elm St.”;
$streets[2] = “Oak Dr.”;

If you use sort() to sort an array with words as keys, the keys are changed to numbers, and the word keys are thrown away.

To sort arrays that have words for keys, use the asort statement as follows:

asort($capitals);

This statement sorts the capitals by value, but it keeps the original key for each value instead of assigning a number key. For example, consider the state capitals array created in the preceding section:

$capitals[‘CA’] = “Sacramento”;
$capitals[‘TX’] = “Austin”;
$capitals[‘OR’] = “Salem”;

You use the following asort statement,
asort($capitals);

The array becomes as follows:

$capitals[‘TX’] = Austin
$capitals[‘CA’] = Sacramento
$capitals[‘OR’] = Salem

Notice that the keys stayed with the value when the elements were reordered. Now the elements are in alphabetical order, and the correct state key is still with the appropriate state capital. If the keys has been numbers, the numbers would now be in a different order. For example, suppose the original array was as follows:

$capitals[1] = “Sacramento”;
$capitals[2] = “Austin”;
$capitals[3] = “Salem”;

After an asort statement, the new array would be as follows:

$capitals[2] = Austin
$capitals[1] = Sacramento
$capitals[3] = Salem

It’s unlikely that you want to use asort on an array with numbers as a key.
 
Last edited:
Back
Top