Image

PHP - Looping - Looping

Looping

PHP While loop

The while loop checks the expr and if it evaluates as true, the script runs through the entire contents of the while until it finishes, then it evaluates the expr again and repeats until the expr evaluates as false.

Example:
$x = 1;
while ($x <= 3){
echo "$x, ";
$x++; // increments $x by adding 1. Short-hand version
}
O/P
1, 2, 3,

PHP Do While loop

The do-while loop performs whatever is inside the do statement, checks the expr, then if it evaluates as TRUE, runs through the entire contents of the do until it finishes, evaluating the expr again, and repeating until the expr evaluates as FALSE.

Example:
$x = 1;
do {
echo "$x, ";
$x++; // Makes $x = 2, therefore the while will evaluate as false
} while ($x <= 1);
O/P
1,