PHP Tutorial on Do While Loops with Stone River eLearning

Taking a break from the concepts of array and topics related to that, in this blog post, we are going to have a look back at the loop statements that we discussed earlier in this series of blogs. We have already studied about For Loops and While Loops and we hope that you have started using them in your PHP scripts to get more comfortable with them. The shortcut behind learning PHP is to stop looking for shortcuts and try investing as much time as you can in exploring on the text editor. The more you succeed, the more you will try to learn.

The flow control statement that we are going to discuss today is the ‘Do.. While’ loop.  The do while loop is an extension to the WHILE loop with a small difference in the syntax part of both the statements.  As we saw in the blog on the WHILE loop, it provides the condition first and then the operation to be performed, however; DO..WHILE on the other hand employs an exactly opposite approach. In a DO…WHILE loop, the operation to be performed is given first followed by the condition at the end of every loop.



do // the do statement which will provide the operation to be performed
  echo "The number $x is smaller than our required value
while($x<=10) //While loop condition provided at the end


 I am sure many of you will be thinking, how is ‘DO..WHILE’ different from ‘WHILE’? Is it just the sequence of steps of execution that is different in the two? Well, certainly not. If you look closely you will realise that in the given example the DO…WHILE loop will execute the string inside the echo function at least once, even if the WHILE condition is not satisfied. This happens for the simple reason that the echo statement is executed first and then the condition is checked.  However, the same is not true with WHILE statement which checks the condition first.


A ‘do.. while’ loop is a great utility in cases when the test result is required beforehand to determine whether or not to perform the operation. Taking a real time example into consideration, a do while loop would come in handy when you need to print the greater number between two given numbers and till they are greater than 0.


Online Technology Courses Stone River eLearning