In tutorial 3, we saw there are loops that we can use to avoid writing long programs. After learning for and foreach loop, we will learn while and do while loops.
While loop is used when we are to display a statement only against a certain condition. If the condition mentioned in the while loop is true, the next statement following the while loop will be executed, otherwise not.
The syntax for using while loop is:
While (condition) { Your statement; }
Example,
<?php $x=0; while($x<3) { echo "Hello <br>"; ++$x; } ?>
The output is:
Hello
Hello
Hello
In while loop, according to the mentioned condition, “Hello” is displayed till the value of $x is less than 3. For, value of x=0, “Hello” is displayed since 0 is less than 3. 0 gets incremented to 1 by ++$x. Now, the value of x, 1 is also less than 3 and the output is “Hello”. But the value is again incremented to 2, which is forwarded to the loop again. 2 is less than 3 and we get “Hello”. As 2 gets incremented this time, condition in the while loop becomes false and the loop then exits. Thus “Hello” is displayed only 3 times.
Do while
In comparison to while loop, do-while loop always displays the value or at least once whether the condition in the while loop is true or not. The syntax using do-while is:
Do { Your statement; } While (condition)
The example is as below:
<?php $x=2; do { echo "how are you?"; ++$x; } while($x>5) ?>
The output will be:
how are you?
Because 2 is not greater than 5, the condition in the while statement becomes false. Still, as we have do statement, it will be executed and we get the output. This would not be the result if only while would have been used. This is the difference between while and do-while loop.
<?php $x=2; do { echo "how are you? <br>"; ++$x; } while($x<5) ?>
The output is: how are you? how are you? how are you? Here, the condition comes out to be true and do statement is executed. The output will be shown till the time this condition is false. Thus, “how are you?” is shown three times.
<?php $x=2; do { echo "how are you?"; ++$x; } while($x>5) ?>
Now that you know how to use WHILE and DO WHILE loop in PHP, continue with the next PHP tutorial on creating forms using PHP. Also, if you have any queries, please leave a comment below.
1 Comment
very good to learn this document
thank u soo much….. and giv full details of php