Once you understand the basics of the for loop structure, you can modify it in a couple of interesting ways. You can build a loop that counts by fives, or one that counts backwards.
The countByFive.php program shown in Figure 4.4 illustrates a program that counts by fives.
The program is very much like the basicArray program, but with a couple of twists.
<html> <head> <title> Counting By Fives </title> </head> <body> <h1>Counting By Fives</h1> <? for ($i = 5; $i <= 50; $i+= 5){ print "$i <br>\n"; } // end for loop ?> </body> </html>
The only thing I changed was the various parameters in the for statement. Since it seems silly to start counting at 0, I set the initial value of $i to 5. I decided to stop when $i reached 50 (after ten iterations). Each time through the loop, $i will be incremented by 5. The += syntax is used to increment a variable.
$i += 5;
is exactly like
$i = $i + 5;
It is fairly simple to modify a for loop so it counts backwards. Figure 4.5 illustrates this feat.
Once again, the basic structure is just like the basic for loop program, but by changing the parameters of the for structure I was able to alter the behavior of the program. The code for this program shows how it is done.
<html> <head> <title> Counting Backwards </title> </head> <body> <h1>Counting Backwards</h1> <? for ($i = 10; $i > 0; $i--){ print "$i <br>\n"; } // end for loop ?> </body> </html>
If you understand how for loops work, the changes will all make sense. I'm counting backwards this time, so $i begins with a large value (in this case 10.) The condition for continuing the loop is now $i > 0, which means the loop will continue as long as $i is greater than zero. As soon as $i is zero or less, the loop will end. Note that rather than adding a value to $i, this time I decrement by one each time through the loop. If you're counting backwards, you must be very careful that the sentry variable has a mechanism for getting smaller, or the loop will never end. Recall that $i++ adds one to $i. $i- - subtracts one from $i.