PHP For Loop

••• PHP For Loop

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:

  1. 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.
  2. At the start of each iteration of the loop, expression2 is tested. If it’s true, the loop continues and the code inside the braces ({}) is run. If it’s false 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 a while loop.
  3. 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


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.