PHP While Loop

Submitted by: 
Language: 
Visitors have accessed this post 5357 times.

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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.