PHP FOR Loop

Started by VelMurugan, Apr 28, 2009, 06:43 PM

Previous topic - Next topic

VelMurugan

PHP FOR Loop

FOR is used in PHP to execute the same code a set number of times. The basic syntax of FOR is as follows:

FOR (expression 1, expression 2, expression 3)
{
  [code to execute]
}

FOR tells PHP to first execute "expression 1", then evaluate "expression 2". If "expression 2" is true, then [code to execute] is executed. After this, expression 3 is executed, and then "expression 2" is evaluated again. If "expression 2" is true, then [code to execute] is executed for a second time. The cycle continues until "expression 2" is no longer true.

Let's look at an example. Assuming we have the following piece of code:

FOR ($i = 0; $i <= 2; $i++)
{
  print "value is now " . $i . "
";
}

The output of the above code is:

value is now 0
value is now 1
value is now 2

During the 1st iteration, $i = 0, which means the expression, ($i <= 2), is true. Therefore, the print statement is executed, and $i gets incremented by 1 and becomes 1.

During the 2nd iteration, $i = 1, which means the expression, ($i <= 2), is true. Therefore, the print statement is executed, and $i gets incremented by 1 and becomes 2.

During the 3rd iteration, $i = 2, which means the expression, ($i <= 2), is true. Therefore, the print statement is executed, and $i gets incremented by 1 and becomes 3.

During the 4th iteration, $i = 3, which means the expression, ($i <= 2), is false. Therefore, PHP exits out of the FOR loop, and does not execute the print statement.