Home > Articles > Programming > PHP

This chapter is from the book

This chapter is from the book

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.

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.