Skip to main content

PHP While Loop


A While Loop can do a repetitive task that an if…then statements can’t. Just like if…then statement, it checks whether the condition is true or false.

There are two different usage of While loop.

while – it first check if the condition is true.
do…while – it execute the code within the loop first, then check if the condition is true and execute it again.

The while loop

While loop syntax

  1. while (condition)
  2. {
  3. code to be executed;
  4. }

Example:

  1. $i = 1;
  2. while ($i <= 10) {
  3. echo "counter = " . $i . "<br />";
  4. $i++;
  5. }

Output:

  1. Counter = 1
  2. Counter = 2
  3. Counter = 3
  4. Counter = 4
  5. Counter = 5
  6. Counter = 6
  7. Counter = 7
  8. Counter = 8
  9. Counter = 9
  10. Counter = 10

The while loop while execute the code until it reaches the value of 10.

The do…while loop

The do…while loop executes differently. Unlike the while loop, it first execute the code once then check if the statement is true.

  1. do
  2. {
  3. code to be executed;
  4. }
  5. while (condition);

Example:

  1. $i = 1;
  2. do
  3. {
  4. $i++;
  5. echo "counter = " . $i . "<br />";
  6. }
  7. while ($i <= 10);

The code above will still have an output the same as the While loop statement. Except that if the variable i ($i) becomes 10.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.