Do while Loop
The “do while” statement executes the loop at least once. Then it checks for the condition and repeats the loop as long as the condition is true.
The basic difference between the while and do while loop is that in while loop the condition is first checked and then loop is executed. In do while loop the loop is executed at least once and then the condition is checked. If the condition is true only then the loop will execute further.
| Syntax |
do
{
Code to be executed;
}
While (condition); |
| |
While (condition)
In the following example we are using the do while loop which executes the block of code at least once and then checks the condition. If the condition is true it will execute the block of code till the condition becomes false.
Example: |
|
<html> |
<body> |
|
<?php |
$a=1; |
do |
{ |
echo "Welcome to floor " . $a . "<br />"; |
$a++; |
} |
while ($a<5); |
?> |
|
</body> |
</html> |
| |
Output

For Loop
The “for” loop in PHP works in the same way as it does in other languages. The “for” loop is used when you already know that how many times a statement or a block of statements has to be executed.
The “for” loop has three parameters. The first parameter in the for loop initializes the variable, the second parameter checks for the condition and the third parameter is for increments required to implement the loop. If there is more than one variable in either the initialization or increment part then they should be separated by commas.
| Syntax |
For (initialization; condition; increment)
{
code to be executed;
}
|
| |
In the following example “Welcome to expertrating.com!” has to be displayed for five times on the browser. So, for this we use the “for” loop as we already know that for how many times the loop should run.
Example |
|
<html> |
<body> |
|
<?php |
for ($i=1; $i<=5; $i++) |
{ |
echo "Welcome to expertrating.com!<br/>"; |
} |
?> |
|
</body> |
</html> |
|