Looping in PHP – For, While and DoWhile

PHP

Loops allow you to repeat certain lines of code. The code is executed repeatedly until a condition is met. This saves you time and also decreases the number of lines of code that you need to have.

For Loop

This loop specifies the condition and repeats the statements as long as the conditions are met.

Example:

<?php
for($i=1;$i<=5;$i++)
{
echo "I = ".$i;
echo "<br />";
}
?>
Output:
I = 1
I = 2
I = 3
I = 4
I = 5

While Loop

This loop is used to specify the condition at first. If required, you will have to set the initial value and make the increments yourself.

Example:

<?php
$i=1;
while($i<=5){
echo "I = ".$i;
echo "<br />";
$i++;
}
?>
Output:
I = 1
I = 2
I = 3
I = 4
I = 5

Do While Loop

This loop is used to execute a block of code within the loop at first. Then at the end of the loop, the condition is checked. The lines of codes within the loop is executed at least once.

<?php
$i=1;
do{
  echo "I = ".$i;
  $i++;
echo "<br />";
}while($i<=5);
?>
Output:
I = 1
I = 2
I = 3
I = 4
I = 5

Difference Between While and Do While Loop

In While loop, the condition is checked at first and the statements are executed. In Do While loop, the statements are executed at first. Then the condition is checked and if it is TRUE, the loop is repeated. In Do While loop, the blocks of code are executed at least onxe even if the condition is not satisfied. While on the other hand exits the loop without performing the statements if the conditions are not satisfied from the beginning.

Example:

<?php
$i=5;
while($i<5){
  echo "While loop prints: ".$i;
$i++;
}
do{
echo "Do while loop prints: ".$i;
$i++;
}while($i<5);
?>
Output:
Do while loop prints: 5
Note: Notice how the output from the While loop are not printed.

There is another type of loop called For Each. This loop is discussed with examples in Arrays in PHP.