PHP Tutorials – Loops
In this PHP Tutorial you will learn about Loops – while loop, do-while loop and the for loop along with syntax and sample PHP loop codes.
while loop:
A while statement executes a code block until a condition is set.
Example:
<?php
$x = 3;
while($x != 0) {
echo $x;
$x–;
}
?>
The while block will be executed three times, and the values 3, 2, and 1 will be printed, at then the value of $x will be zero, which causes the loop to exit.
do-while loop:
The main difference between the while loop and the do-while loop is that the do-while loop is guaranteed to execute at least once, even if the condition evaluates to false.
The while loop checks the condition before executing the while block, so if the condition returns false, the block won’t be executed.
The do-while block executes the block, then checks for the condition.
Example:
<?php
$x = 5;
do {
echo $x;
$x++;
} while ($x < 4);
?>
The above script will print the value of $x which is 5, then will check for the condition, it will return false, so the loop will stop.
for loop:
This is can be used when the times of execution is known or can be evaluated.
Example:
<?php
for($i = 0; $i < 5; $i++) {
echo $i;
}
?>
The above script will echo the numbers from 0 to 4.
A for loop has three parts:
1. Initialization expression ($i = 0): has to be executed at the beginning of the loop.
2. Loop condition ($i < 5): has to return true for the loop to continue.
3. Increment expression ($i++): executed at the end of the loop, before testing the condition.
Any of the for loop parts can be skipped, for example:
<?php
$i = 0;
for(; i < 7; i++) {
// Code to be executed
}
?>
The expression for( ; ; ) creates an infinite loop.