Using the foreach loop to Work with an Array

Using the foreach loop to Work with an Array

As I mentioned in Chapter 4, "Loops and Arrays: The Poker Dice Game," for loops and arrays are natural companions. In fact, PHP supplies a special kind of loop that makes it even easier to step through each element of an array.

Introducing the foreach.php Program

The program shown in Figure 5.4 illustrates how the foreach loop works.

Click To expand
Figure 5.4: Although it looks just like normal HTML, this page was created with an array and a foreach loop.

The HTML page is unremarkable, but it was generated by surprisingly simple code.

<title>Foreach Demo</title>
<h1>Foreach Demo</h1>

$list = array("alpha", "beta", "gamma", "delta", "epsilon");

print "<ul>\n";
foreach ($list as $value){
  print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";


All the values that will be in the list are created in the $list variable using the array function.

The foreach loop works a lot like a for loop, except it is a bit simpler. The first parameter of the foreach construct is an array (in this case, $list). The keyword as then indicates the name of a variable that will hold each value in turn. In this case, the foreach loop will step through the $list array as many times as necessary. Each time through the loop, the function will populate the $value variable with the current member of the $list array. In essence, this foreach loop:

foreach ($list as $value){
  print " <li>$value</li>\n";
} // end foreach

works just like the following traditional for loop:

for ($i = 0; $i < length($list); $i++);
  $value = $list[$i];
  print " <li>$value</li>\n";
} // end for loop


The main difference between a foreach loop and a for loop is the presence of the index variable ($i in this example). If you're using a foreach loop and you need to know the index of the current element, you can use the key() function.

The foreach loop can be an extremely handy shortcut for stepping through each value of an array. Since this is a common task, knowing how to use the foreach loop is an important skill. As you learn some other kinds of arrays, you'll see how to modify the foreach loop to handle these other array styles.