PHP While Loop Tutorial

A while loop is a method of repeating a task as long as a certain condition holds. For example, you may want to keep prompting a user to enter a value as long as they keep entering an invalid one. In other words, the while loop is useful when you don't know how many times you want to carry out a set of instructions.

If you do know how many times you want to repeat a set of instructions, the PHP for loop is a better choice of loop to use.

As said above, the while loop is used when you don't know at first how many times you want the code to be executed, but you know for sure when you want it to stop being executed. The PHP while loop tutorial below explains.

PHP While Loop Syntax

The While Loop in PHP is defined as follows:

while (condition)
{
    // do some stuff
}

The while loop works by first checking if a condition is true.If the condition is true, then the code within the curly braces is executed and will keep executing over and over until the condition changes to false. That is, in order for the script to exit the loop, it must be possible to change the condition from inside the loop or else there will be no other way to stop it.

The last statement above is not exactly true as we can also use a PHP break statement to exit the loop. Since we have not covered that technique in our tutorials, we consider changing the condition the only way to exit the loop.

Be careful not to write loops that cannot be terminated (or are very long) as this will cause your script to hang inside the loop, perhaps indefinitely.

If we need the loop to execute at least once before checking the condition, a variant of the while loop, known as the do while loop is better suited for this task.

PHP While Loop Example

An example of using a while loop in PHP is shown below:

<?php
 
    $total = 1;
 
    while ($total <= 10)
    {
        echo $total . '-' . ($total * 10);
        echo '<br />';
        $total++; // important line explained below
    }
?>

Result:

1-10
2-20
3-30
4-40
5-50
6-60
7-70
8-80
9-90
10-100

The line that was marked important is important because it keeps increasing the variable $total. If we did not increase this variable, our loop would have no way of ending since it would always be 1 and hence always less than or equal to 10. This would cause our script to hang inside of the loop and is an excellent example of what not to do.

Using loops, you can elegantly do a large number of similar tasks as you saw in the example above. We hope that you learnt a lot in our PHP while loop tutorial.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...