Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here’s the syntax for a while loop,

Ex:

while (condition) {
statement
}

And here’s some code to try. All it does is increment a variable called counter:

$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
"); $counter++; }

The condition to test for is $counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When $counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.

If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the $counter variable is incremented. Like this:

Ex:

$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
"); //$counter++; }

Notice the two forward slashes before $counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – $counter will always be 1.

Here’s a while loop that prints out the 2 times table. Try it out in a script.

$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "
"); $start++; }