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]; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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