The for Loop

The while and do-while loops are fairly simple: they repeat for so long as the specified
condition remains true. But PHP also supports a more sophisticated type of loop, the for
loop, which is useful when you need to execute a set of statements a specific number of
times.
The best way to understand a for loop is by looking at some code. Here’s a simple
example, which lists the numbers between 1 and 10:
<?php
// repeat continuously until counter becomes 10
// output:
for ($x=1; $x<10; $x++) {
echo “$x “;
}
?>
In this listing, the loop begins by initializing the counter variable $x to 1; it then
executes the statements that make up the loop. Once it reaches the end of the first loop
iteration, it updates the loop counter by adding 1 to it, checks the conditional expression to
ensure that the counter hasn’t yet reached 10, and executes the loop once more. This process
continues until the counter reaches 10 and the conditional expression becomes false.
As this listing illustrates, there are thus three expressions involved in the typical for
loop, separated by semicolons and enclosed in parentheses:
● The first of these is an assignment expression, which initializes the loop counter to a
specific value—in this case, assigning the value 1 to the variable $x.
● The second is a conditional expression, which must evaluate to either true or false;
the loop will continue to execute so long as this condition remains true. Once the
condition becomes false, the loop will stop executing.
● The third is again an assignment expression, which is executed at the end of each loop
iteration, and which updates the loop counter with a new value—in this case, adding 1
to the value of $x.

Twitter Widgets Facebook Widgets

For Further Reading:

Leave a Comment


Previous post:

Next post: