ptg16476052
664 LESSON 24: Taking Advantage of the Server
for Loops
Use for loops when you want to run a loop a specific number of times. The loop state-
ment has three parts: a variable assignment for the loop’s counter, an expression (con-
taining the index variable) that specifies when the loop should stop running, and an
expression that increments the loop counter. Here’s a typical for loop:
for ($i = 1; $i <= 10; $i++)
{
echo "Loop executed $i times.\n";
}
$i is the counter (or index variable) for the loop. The loop is executed until $i is larger
than 10 (meaning that it will run 10 times). The last expression, $i++, adds one to $i
every time the loop executes. The for loop can be used instead of foreach to process an
array. You just have to reference the array in the loop statement, like this:
$colors = array('red', 'green', 'blue');
for ($i = 0; $i < count($colors); $i++) {
echo "Currently processing ". $colors[$i]. ".\n";
}
There are a couple of differences between this loop and the previous one. In this case, I
start the index variable at 0 and use < rather than <= as the termination condition for the
loop. That’s because count() returns the size of the $colors array, which is 3, and loop
indexes start with 0 rather than 1. If I start at 0 and terminate the loop when $i is equal to
the size of the $colors array, it runs three times, with $i being assigned the values 0, 1,
and 2, corresponding to the indexes of the array being processed.
while and do...while Loops
Both for and foreach are generally used when you want a loop to iterate a specific num-
ber of times. The while and do...while loops, on the other hand, are designed to be run
an arbitrary number of times. Both loop statements use a single condition to determine
whether the loop should continue running. Here’s an example with while:
$number = 1;
while ($number != 5) {
$number = rand(1, 10);
echo "Your number is $number.\n";
}
This loop runs until $number is equal to 5. Every time the loop runs, $number is assigned
a random value between 1 and 10. When the random number generator returns a 5, the