
|
|
|||
Sorting an Array in PHPBy Amrit Hallan2005-11-14
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:
The output of this PHP code is: Alfred Now we apply the sort() function and see what happens.
The output of this PHP code is: Alfred 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:
Now the output is: Vladimir 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:
The outcome you get is: 0 = Computer Associated 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:
The result is: CA = Computer Associated 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:
Similarly, you can sort an associative array according to the key, in ascending order by using the krsort() function. Tutorial Pages: » Sorting an Array in PHP |
||||
| About the NetVisits, Inc Network | Write For Us | Advertise Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy. |
Visit other NetVisits, Inc. sites: |