- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
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