PHP While Loop

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

Previous topic - Next topic

VelMurugan

PHP While Loop

WHILE is used in PHP to provide a control condition. The basic syntax of WHILE is as follows:

WHILE (expression)
{
  [code to execute]
}

WHILE tells PHP to execute the [code to execute] as long as the (expression) is true.

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

$counter = 8;
WHILE ($counter < 10)
{
  print "counter is now " . $counter . "<br>";
  $counter++;
}


The output of the above code is:

counter is now 8
counter is now 9

During the first iteration, $counter = 8, which means the expression, ($counter < 10), is true. Therefore, the print statement is executed, and $counter gets incremented by 1 and becomes 9.

During the second iteration, $counter = 9, which means the expression, ($counter < 10), is true. Therefore, the print statement is executed, and $counter gets incremented by 1 and becomes 10.

During the third iteration, $counter = 10, which means the expression, ($counter < 10), is false. Therefore, the WHILE condition no longer is true, and the code in the bracket is no longer executed.