The for loop is used when you know how many times the code should run.

Syntax:

for (init; condition; increment)
{
code to be executed;
}

Description:

The first argument “init” Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)

The second argument “condition” Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

The third argument “increment” Mostly used to increment a counter (but can be any code to be executed at the end of the loop)

Each of the expressions can be empty or contain multiple expressions separated by commas.

Example1:
Code:

for ($i = 2; $i <= 6; $i++)
 {
    echo $i;
}

Output:

2 3 4 5 6

Example2:
Code:


for  ($i = 2; ; $i++) {
      if ($i > 6) {
        break;
    }
    echo $i."
"; }

Output:

2 3 4 5 6

Example3:
Code:

$i = 2;
for (; ; ) {
    if ($i > 6) {
        break;
    }
    echo $i."
"; $i++; } Output: 2 3 4 5 6

Example4:
Code:

for ($i = 2, $j = 0; $i <= 6; $j += $i, print $i, $i++);

Output:

2 3 4 5 6

eXTReMe Tracker