Skip to main content

PHP While Loop

Body

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. <br />
  2. while (condition)<br />
  3. {<br />
  4. code to be executed;<br />
  5. }<br />

Example:

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

Output:

  1. <br />
  2. Counter = 1<br />
  3. Counter = 2<br />
  4. Counter = 3<br />
  5. Counter = 4<br />
  6. Counter = 5<br />
  7. Counter = 6<br />
  8. Counter = 7<br />
  9. Counter = 8<br />
  10. Counter = 9<br />
  11. Counter = 10<br />

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. <br />
  2. do<br />
  3. {<br />
  4. code to be executed;<br />
  5. }<br />
  6. while (condition);<br />

Example:

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

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