}
?>
The loop block checks whether $i is greater or equal to 10 and, if that
condition is true, adds 1 to $i and prints it. Then it goes back to the loop
condition again. Because $i starts at 10 and you only ever add numbers to it,
that loop continues forever. With two small changes, you can make the loop
count down from 10 to 0:
Click here to view code image
<?php
$i = 10;
while ($i >= 0) {
$i -= 1;
echo $i;
}
?>
So, this time you check whether $i is greater than or equal to 0 and subtract 1
from it with each loop iteration. You typically use while loops when you are
unsure how many times the code needs to loop because while keeps looping
until an external factor stops it.
With a for loop, you specify precise limits on its operation by giving it a
declaration, a condition, and an action. That is, you specify one or more
variables that should be set when the loop first runs (the declaration), you set
the circumstances that will cause the loop to terminate (the condition), and
you tell PHP what it should change with each loop iteration (the action). That
last part is what really sets a for loop apart from a while loop: You usually
tell PHP to change the condition variable with each iteration.
You can rewrite the script that counts down from 10 to 0 by using a for loop:
Click here to view code image
<?php
for($i = 10; $i >= 0; $i -= 1) {
echo $i;
}
?>
This time you do not need to specify the initial value for $i outside the loop,
and you also do not need to change $i inside the loop; it is all part of the for
statement. The actual amount of code is really the same, but for this purpose,
the for loop is arguably tidier and therefore easier to read. With the while
loop, the $i variable was declared outside the loop and so was not explicitly
attached to the loop.