Home /PHP/While Loop

While Loop

PHP while loops are similar to for loops, but with a different structure. Personally, I use for loops much more often than I use while loops. However, while loops have their own powerful uses that you will discover later in your programming life.

Example

$i = 0;
while($i < 5)
{
    echo $i; //write our variable’s value
    echo "<br/>"; //line break
    $i++; //increment operator
}
echo "End of while loop";

Result

0
1
2
3
4
End of while loop

After seeing the while loop, you can probably see how it is like the for loop, but with the first statement outside of the loop, the conditional in the if-like statement, and the second statement embedded within the loop.

The first statement $i = 0; is simply setting our variable $i equal to zero. The conditional statement $i < 5 serves as the only item in the if-like statement. Finally, the embedded code includes our increment operator $i++;, which advances the if-like statement. From the results, we can see that the exact same thing happens here as in the previous for loop.

Example

$i = 0;
do
{
    echo $i; //write our variable’s value
    echo "<br/>"; //line break
    $i++; //increment operator
}
while($i < 5);

Result

0
1
2
3
4

Again, this is pretty similar to the example above, but there is one major difference. In the do while loop, the statements in the do block are always run at least once because the conditional is checked at the end. The conditional then tells PHP to go back and run through the do block again if the condition is still true.

We set the variable $i equal to 0. Then, we run through the do block, where the increment operator $i++; advances the loop. The results are the same as the previous loops. Once the increment operator makes $i equal to 5, we exit the loop and continue reading the next statement, echo "End of while loop";.

PHP While Loop Iteration

The diagram above shows how PHP loops or iterates through a while loop. If the condition is met, PHP executes the code in the parentheses after the while loop. After executing that code, PHP returns to the while loop condition and checks to see if the condition is true. If it is true, the code in the while loop is executed again. This process continues until the condition is no longer true.