PHP For Loop
Updated Jan 9, 2021 View by 1.5 K

In this tutorial, you will learn about PHP For Loop statement to execute a block of code predetermined number of times. The for
loop is used when you know in advance how many times the script should run.
Introduction to PHP For Loop
The for
loop statement is the most complex loop statement in PHP. You often use the PHP for
loop statement when the number of executions is predetermined. Even though, the PHP for
loop statement provides more functionality than that.
Syntax of PHP For Loop
for ( expression1; expression2; expression3 ) { // This code is run as long as expression2 is true } // This code is run after the loop finishes
You can see that for
loops are more complex than while loops and do while loops whereas a while
loop has 1 expression between the parentheses, a for
loop has 3 expressions, separated by semicolons.
Here’s how a for
loop works:
- The first time through the loop, the PHP engine evaluates
expression1
. This expression is known as the initializer, and is usually used to set up a counter variable for the loop. - At the start of each iteration of the loop,
expression2
is tested. If it’strue
, the loop continues and the code inside the braces ({}) is run. If it’sfalse
the loop exits, and any code after the closing brace is run.expression2
is known as the loop test, and serves the same purpose as the single expression in awhile
loop. - After each iteration, the PHP engine evaluates
expression3
. This expression is known as the counting expression, and is usually used to change the counter variable.
Example of PHP For Loop
<?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?>
Output of the above Code:
The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10
Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE
, like C). This may not be as useless as you might think, since often you’d want to end the loop using a conditional break statement instead of using the for truth expression.