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.

Add new comment