Skip to main content

Examples of looping through arrays in PHP.

<?php

// -----------------------------------------------------------------
// Walking through a numeric array using foreach...as
// -----------------------------------------------------------------

$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;

foreach ($paper as $item) {
  echo "$j: $item <br>";
  ++$j;
}

// -----------------------------------------------------------------
// Walking through an associative array using foreach...as
// -----------------------------------------------------------------

$paper = array(
  'copier' => "Copier & Multipurpose",
  'inkjet' => "Inkjet Printer",
  'laser'  => "Laser Printer",
  'photo'  => "Photographic Paper"
);

foreach ($paper as $item => $description) {
  echo "$item: $description<br>";
}

// -----------------------------------------------------------------
// Walking through an associative array using each and list
// -----------------------------------------------------------------

$paper = array(
  'copier' => "Copier & Multipurpose",
  'inkjet' => "Inkjet Printer",
  'laser'  => "Laser Printer",
  'photo'  => "Photographic Paper"
);

while (list($item, $description) = each($paper)) {
  echo "$item: $description<br>";
}

?>