Home > Articles


  • Print
  • + Share This

3.8 Accessing Different Areas of an Array

You want to process more than one element of an array at a time.


Use the array_slice() command creatively to have the desired effects:

$mash_cast = array ("Hawkeye",
          "Colonel Blake",
          "Colonel Potter",
          "General Clayton",
          "Frank Burns",
          "Charles Winchester",

$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


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:

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:

$start = 2;
$end = 6;

for ($i = $start; $i <= $end; $i++) {
  $partial_array[] = $orig_array[$i];
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.