PHP while and do...while Loop

As the name suggests, a Loop is used to execute something over and over again.

For example, if you want to display all the numbers from 1 to 1000, rather than using echo statement 1000 times, or specifying all the numbers in a single echo statement with newline character \n, we can just use a loop, which will run for 1000 times and every time it will display a number, starting from 1, incrementing the number after each iteration or cycle.

In a Loop, we generally specify a condition or a LIMIT up till which the loop will execute, because if we don't specify such a condition, how will we specify when the loop should end and not go on for infinite time.

How loops work in pogramming languages


PHP while Loop

The while loop in PHP has two components, one is a condition and other is the code to be executed. It executes the given code until the specified condition is true.

Syntax:

<?php
while(condition)
{
    /* 
        execute this code till the  
        condition is true
    */
}
?>

For example, let's take the problem mentioned in the beginning of this tutorial. Let's print numbers from 1 to 10.

<?php

$a = 1;

while($a <= 10)
{
    echo "$a | ";
    $a++;   // incrementing value of a by 1
}
?>

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |

Note: We have added a symbol | just to separate the numbers, it has no functional use in the above code.


PHP do...while Loop

The do...while loop is a little different from all the loops in PHP because it will execute at least one time, even if the condition is false, can you guess how? Well because the condition is checked after the loop's execution, hence the first time when the condition is checked, the loop has already executed once.

Syntax:

<?php
do {
    /* 
        execute this code till the  
        condition is true
    */
} while(condition)
?>

Let's implement the above example using do...while loop,

<?php

$a = 1;

do {
    echo "$a | ";
    $a++;   // incrementing value of a by 1
} while($a <= 10)
?>

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |


Let's take another example where even if the condition is false, still the loop will be executed once.

<?php

$a = 11;

do {
    echo $a;
    $a++;   // incrementing value of a by 1
} while($a <= 10)
?>

11

As we can see clearly, that the condition in the above do...while loop will return false because value of variable $a is 11 and as per the condition the loop should be executed only if the value of $a is less than or equal to 10.