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.
<?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.
<?php $paper = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.