Merging and Splitting Arrays


You can also cut up and merge arrays when needed. For example, say you have a three-item array of various fruits and want to get a subarray consisting of the last two items. You can do this with the array_slice function, passing it the array you want to get a section of, the offset at which to start, and the length of the array you want to create:

 <?php     $fruits["good"] = "tangerine";     $fruits["better"] = "pineapple";     $fruits["best"] = "pomegranate";     $subarray = array_slice($fruits, 1, 2);     foreach ($subarray as $value) {         echo "Fruit: $value\n";     } ?> 

Here are the results:

 Fruit: pineapple Fruit: pomegranate 

If offset is negative, the sequence will be measured from the end of the array. If length is negative, the sequence will stop that many elements from the end of the array.

NOTE

If you don't give the length of the subarray you want, you'll get all the elements to the end (or the beginning, if you're going in the opposite direction) of the array.


You can also merge two or more arrays with array_merge:

 <?php     $fruits = array("pineapple", "pomegranate", "tangerine");     $vegetables = array("corn", "broccoli", "zucchini");     $produce = array_merge($fruits, $vegetables);     foreach ($produce as $value) {         echo "Produce item: $value\n";     } ?> 

And here's what you get (see also "Using the Array Operators" in this chapter):

 Produce item: pineapple Produce item: pomegranate Produce item: tangerine Produce item: corn Produce item: broccoli Produce item: zucchini 



    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