- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.8 Accessing Different Areas of an Array
You want to process more than one element of an array at a time.
Technique
Use the array_slice() command creatively to have the desired effects:
<?php $mash_cast = array ("Hawkeye", "Trapper", "Honeycutt", "Radar", "Klinger", "Colonel Blake", "Colonel Potter", "General Clayton", "Frank Burns", "Charles Winchester", "Hotlips"); $side_kicks = array_slice ($mash_cast,1,2); // Trapper, Honeycutt $annoyances = array_slice ($mash_cast,-3,3); // Frank Burns, Charles Winchester, Hotlips $assistants = array_slice ($mash_cast,3,2); // Radar, Klinger $officials = array_slice ($mash_cast,5,3); // Colonel Blake, Colonel Potter, General Clayton $main_character = array_slice ($mash_cast,0,1); // Hawkeye ?>
Comments
The syntax of the array_slice() function is similar to array_splice() (if you omit the replacement array parameter), which is covered in recipe 3.4. This recipe illustrates how to get information out of arrays. In these examples, we assigned the values returned from array_slice() to new arrays, but you can also assign them to variables:
<?php list ($var1, $var2) = array_slice ($ar, 0, 2); // grab the first two items of the array and assign them // to $var1 and $var2. ?>
If you are still coding in PHP 3 (upgrade already) and therefore the array_slice() function is not available to you, you can use the following method to work with a range of elements:
<?php $start = 2; $end = 6; for ($i = $start; $i <= $end; $i++) { $partial_array[] = $orig_array[$i]; } ?>