Sorting Arrays


PHP offers all kinds of ways to sort the data in arrays, starting with the simple sort function, which you use on arrays with numeric indexes. In the following example, we create an array, display it, sort it, and then display it again:

 <?php     $fruits[0] = "tangerine";     $fruits[1] = "pineapple";     $fruits[2] = "pomegranate";     print_r($fruits);     sort($fruits);     print_r($fruits); ?> 

Here are the resultsas you can see, the new array is in sorted order; note also that the elements have been given new numeric indexes:

 Array (     [0] => tangerine     [1] => pineapple     [2] => pomegranate ) Array (     [0] => pineapple     [1] => pomegranate     [2] => tangerine ) 

You can sort an array in reverse order if you use rsort instead:

 <?php     $fruits[0] = "tangerine";     $fruits[1] = "pineapple";     $fruits[2] = "pomegranate";     print_r($fruits);     rsort($fruits);     print_r($fruits); ?> 

Here's what you get:

 Array (     [0] => tangerine     [1] => pineapple     [2] => pomegranate ) Array (     [0] => tangerine     [1] => pomegranate     [2] => pineapple ) 

What if you have an array that uses text keys? Unfortunately, if you use sort or rsort, the keys are replaced by numbers. If you want to retain the keys, use asort instead, as in this example:

 <?php     $fruits["good"] = "tangerine";     $fruits["better"] = "pineapple";     $fruits["best"] = "pomegranate";     print_r($fruits);     asort($fruits);     print_r($fruits); ?> 

Here are the results:

 Array (     [good] => tangerine     [better] => pineapple     [best] => pomegranate ) Array (     [better] => pineapple     [best] => pomegranate     [good] => tangerine ) 

You can use arsort to sort arrays such as this in reverse order. What if you wanted to sort an array such as this one based on keys, not values? Just use ksort instead. To sort by reverse by keys, use krsort. You can even define your own sorting operations with a custom sorting function you use with PHP's usort.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net