PHP WHILE Loop


PHP Tutorial > 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.

Next: PHP FOR Loop

Link to this page: If you find this page useful, we encourage you to link to this page. Simply copy and paste the code below to your website, blog, or profile.






Copyright 1keydata.com 2007, 2008, All Rights Reserved.   Privacy Policy  



PHP Tutorial
PHP Variables
PHP Operators
PHP IF ELSE
PHP ELSEIF
PHP Switch
PHP While Loop
PHP FOR Loop
PHP DO WHILE Loop
PHP FOREACH Loop
PHP INCLUDE
PHP Functions
PHP ARRAY
PHP FORMS
PHP Cookies
PHP Redirect
PHP MySQL

PHP Commands

Resources