PHP Loops
ADVERTISEMENTS
PHP has the four types of loop statement which is listed here:
- While Loop
- Do-While Loop
- For Loop
- Foreach Loop
PHP While Loop
PHP, while loop executes statements and block of code as per specified condition, is true.
Syntax of the while loop
while (condition is TRUE) {
execute a statement;
}
execute a statement;
}
There are given an example of the while loop:
<?php
$m = 4;
while ($m <= 10)
{
echo "Hello World!";
echo "\n";
$m++;
}
?>
Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
PHP Do While Loop
PHP While and Do While loop is the same thing in expression checking at the end of an iteration.
The main difference between While and Do While:
- While loop checks the condition and repeats the block of code while a specified condition is true.
- Do While loop executes the block of code once then check the condition and repeat the block of code while the specified condition is true.
- Do While loop guaranteed checks truth expression.
Syntax of the php do-while loop
do {
execute statements;
} while (condition is TRUE);
execute statements;
} while (condition is TRUE);
There are given an example of the do-while loop:
<?php
$m = 4;
do {
echo "Hello World!";
echo "\n";
$m++;
} while ($m <= 10);
?>
Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
The explanation of the for loop & foreach loop is given on the next page.