The foreach Statement

Oct 13, 2009 Author: LinuxAdmin

The foreach statement is similar to for in that it is basically a specializedform of the while loop. Foreach, however, unlike for, is to be used witharrays.Like for, foreach automatically performs a step for every repetition of the loop: It assigns the next value of an array to a temporary variable (similarto a counter).For example, foreach could be used to sum all of the numbers in an array.The syntax for the foreach loop is as follows:

foreach (array as value)
{
code to repeat
}
In this example, we'll use foreach to print each element of anarray. We 'll step through the array using foreach as discussed previously, printing each element as we go, as follows:
<?php
$arrNames = Array('Joe',
                  'Bill',
                  'Arnie',
                  'Harold');
foreach ($arrNames as $strName)
{
echo $strName . '< br>' ;
}
?>
As you already can see, the output of this program would be thenames in $arrNames printed with each name on a separate line.


views 3549
  1. Add New Comment