Counting with the for Loop

Counting with the for Loop

Computers are good at repetitive behavior. There are many times you might want the computer to repeat some sort of action multiple times. For example, take a look at the simpleFor.php program shown in Figure 4.3.

Click To expand
Figure 4.3: This program counts from zero to one using only one print statement!

While the output of the simpleFor program doesn't look all that interesting, it has a unique characteristic. It has only one print statement in the entire program, which is executed ten different times. Take a look at the source code of this program to see how it works.


A simple For Loop


<h1>A simple for loop</h1>


for ($i = 0; $i < 10; $i++){
  print "$i <br>\n";
} // end for loop



Each number is printed in the line that looks like this:

  print "$i <br>\n";

This line can only print one value, but it happens ten times. The key to this behavior is the for statement. The for structure has three main parts.

Initializing a Sentry Variable

for loops usually involve an integer variable. Sometimes the key variable in a loop is referred to as a sentry variable, because it acts like a gatekeeper to the loop. The first part of a for loop definition is a line of code that identifies the sentry variable and initializes it to some starting value. In the simple for loop demo, the initialization segment looks like this:

$i = 0;

It specifies that the sentry variable will be called $i, and its starting value will be zero.

Start example

You might wonder why the sentry variable is called $i. Like most variables, it's really best if sentry variables have a name that suits their purpose. Sometimes, however, a for loop sentry is simply an integer, and it doesn't really have any other meaning. In those situations, an old programming tradition is often called into play. In the Fortran language (one of the earliest common programming languages) all integer variables had to begin with the letters "i," "j," and a few other characters. Fortran programmers would commonly use "i" as the name of their generic sentry variables. Even though most modern programmers have never written a line of Fortran code, the tradition remains. It's amazing how much folklore exists in such a relatively new activity as computer programming.

End example

Computer programs frequently begin counting with zero, so I initialized $i to zero as well.


Although the $i = 0; segment looks like (and is) a complete line of code, it is usually placed on the same line as the other parts of the for loop construct.

Setting a Condition to Finish the Loop

Getting a computer to repeat behavior is actually the easy part. The harder task comes when you try to get the computer to stop correctly. The second part of the for loop construct is a condition. When this condition is evaluated as true, the loop should continue. As soon as the condition is evaluated to false, the loop should exit. In this case, I set the condition as $i < 10; This means that as long as the variable $i has a value less than 10, the loop continues. As soon as the program detects that $i has a value equal to or larger than 10, the loop exits. Usually a for loop's condition checks the sentry variable against some terminal value.

Changing the Sentry Variable

The final critical element of a for loop is some mechanism for changing the value of the sentry variable. At some point the value of $i must become 10 or larger, or the loop will continue forever. In the basicLoop program, the part of the for structure which makes this happen looks like $i++. The notation $i++ is just like saying 'add one to $i,' or $i = $i + 1. The ++ symbol is called an increment operator because it provides an easy way to increment (add one) to a variable.

Building the Loop

Once you've set up the parts of the for statement, the loop itself is easy to use. Place braces ({}) around your code and indent all code that will be inside the loop. You can have as many lines of code as you wish inside a loop, including branching statements and other loops. The sentry variable will have special behavior inside the loop. It will begin with the initial value. Each time the loop repeats, it will be changed as specified in the for structure, and the interpreter will check the condition to ensure that it's still true. If so, the code in the loop will occur again. In the case of the basicArray program, $i begins as zero. The first time the print statement occurs, it prints out zero, because that is the current value of $i. When the interpreter reaches the right brace that ends the loop, it increments $i by one (following the $i++ directive in the for structure) and checks the condition ($i < 10). Because 0 is less than 10, the condition is true, and the code inside the loop occurs again. Eventually, the value of $i becomes 10, so the condition ($i < 10) is no longer true. Program control then reverts to the next line of code after the end of the loop, which ends the program.