O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The foreach...as Loop

The creators of PHP have gone to great lengths to make the language easy to use. So, not content with the loop structures already provided, they added another one especially for arrays: the foreach...as loop. Using it, you can step through all the items in an array, one at a time, and do something with them.

The process starts with the first item and ends with the last one, so you don’t even have to know how many items there are in an array. Example 6-6 shows how foreach can be used to rewrite Example 6-3.

Example 6-6. Walking through a numeric array using foreach...as
<?php
$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;

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

When PHP encounters a foreach statement, it takes the first item of the array and places it in the variable following the as keyword, and each time control flow returns to the foreach the next array element is placed in the as keyword. In this case, the variable $item is set to each of the four values in turn in the array $paper. Once all values have been used, execution of the loop ends. The output from this code is exactly the same as for Example 6-3.

Now let’s see how foreach works with an associative array by taking a look at Example 6-7, which is a rewrite of the second half of Example 6-5.

Example 6-7. Walking through an associative array using foreach...as
<?php $paper = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required