| Home > Computer & I'net > Sorting Arrays... |
|
|
|||||||||||||||
|
|
|||||||||||||||
|
||||||||||||||||
Sorting Arrays | |
Sorting means organizing a bunch of values in alphabetical or numerical order. PHP can be used to sort an array by it's keys or values. The result can keep the corresponding key/value with the original value/key or replace them. That sounds a bit confusing, so here are the examples to sort it out (couldn't resist the pun). <?php Use the sort command to sort the values with no regard to the keys. The values only will be changed. sort($pantry); The pantry array now looks like this... 0 apples 1 bananas 2 bread 3 oranges 4 potatoes 5 tomatoes The values have changed places into alphabetical order while the keys remain in the same order. To sort the values in reverse order with no regard to the keys, the rsort command is used. rsort($pantry); The pantry array now looks like this... 0 tomatoes 1 potatoes 2 oranges 3 bread 4 bananas 5 apples The values have changed places into alphabetical order while the keys remain in the same order. To sort the values and keep the corresponding keys, the asort command is used. asort($pantry); The pantry array now looks like this... 5 apples 2 bananas 4 bread 1 oranges 3 potatoes 0 tomatoes A similar sorting with keys technique can also be done in the reverse order using the arsort command. arsort($pantry); The pantry array now looks like this... 0 tomatoes 3 potatoes 1 oranges 4 bread 2 bananas 5 apples To sort the keys and keep the values, the ksort command is used. ksort($pantry); The pantry array now looks like this... 0 tomatoes 1 oranges 2 bananas 3 potatoes 4 bread 5 apples In this case, it remains the same as the original array considering the keys were already in numerical order. To sort the keys and keep the values in reverse order, the krsort command is used. krsort($pantry); The pantry array now looks like this... 5 apples 4 bread 3 potatoes 2 bananas 1 oranges 0 tomatoes The shuffle command is used to randomly reorganize the values of an array. The keys remain the same. shuffle($pantry); The pantry array now looks like this... 0 tomatoes
1 bananas 2 potatoes 3 bread 4 apples 5 oranges If you reload this page, the above result will appear different. ----------------- Article by David Stanley. Visit his site http://www.htmlite.com. Reprinted with permission. | |
| Articles |
•Auto & Trucks•Business•Computer & I'net·General·Apache·CSS·Database·Hardware·HTML·Javascript&DHTML·Linux·MySQL·Operating System·Perl / CGIPHP·Programming·Publishing·Search Engines·Software Problems·SSI·Tips & Tricks·Utilities·Web Design•Family•Food & Drink•Gardening•Health•Other•Pets•Psychology•Spiritual•Travel•Women |
| Calculators |
|