PHP While Loop

In PHP, while loop executes a block of codes as long as a given condition or test expression is a true. In this loop, we define the incrementer outside the loop and then increment it inside the loop in a separate statement.

If the given condition or test expression is a true then code block will be executed. After the code is executed, the given condition or test expression will again be evaluated and the loop will continue till the given condition or the test expression is found to be true.

It is very important that there should be some such point inside the loop which makes the condition false ultimately so that it will run endlessly.

Syntax

while (condition is true) {
    //code to be executed;
}

PHP While Loop Example

<?php 
$watchesLeft = 3;
while ( $watchesLeft > 0 ) {
echo "There are $watchesLeft watches left. < br / > ";
}
echo "No watch left!";
?> 

This will produce following result

There are 3 watches left.
There are 2 watches left.
There are 1 watches left.
No watch left.