PHP While Loop
Submitted by admin on Wednesday, June 5, 2013 - 09:57.
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.
Example:
Output:
Example:
The code above will still have an output the same as the While loop statement. Except that if the variable i ($i) becomes 10.
The while loop
While loop syntax- while (condition)
- {
- code to be executed;
- }
- $i = 1;
- while ($i <= 10) {
- echo "counter = " . $i . "<br />";
- $i++;
- }
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Counter = 6
Counter = 7
Counter = 8
Counter = 9
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.- do
- {
- code to be executed;
- }
- while (condition);
- $i = 1;
- do
- {
- $i++;
- echo "counter = " . $i . "<br />";
- }
- while ($i <= 10);
Add new comment
- 200 views