Introduction
Loops executes sets of commands until the condition is true/false. There are four types of loops in PHP, which are as follows:
- While loop
- do...while loop
- for loop
- foreach loop
The While loop
A while loop executes sets of commands until the condition is true. A while loop is also known as entry controls loop because they control entry into the body when condition is true and the condition is tested first.
Syntax of while loop
while (condition)
{
message ; //condition is true
}
Example
The example of while loops are as follows:
<?php
$i=2;
echo ("The table of 2 is using While loop : ".'<br>');
while ($i<=20)
{
echo $i.'<br>';
$i=$i+2;
}
?>
Output
The do...while loop
The do...while loop executes sets of commands at least once. The do...while loop executes set of commands until the condition specified for the while is true and will stop when the condition is false. The do...while loop is also known as an exit control loop.
Syntax of do...while loop
do
{
message ;
}
while (condition) ;
Example
The example of a do...while is as follows:
<?php
echo "The table of 2 is using do...while loop : ".'<br>';
$i=0;
do
{
$i=$i+2;
echo $i . "<br />";
}
while ($i<=20);
?>
Output
The for loop
The for loop is the same as while loop but with the difference that in the for loop initialization, a condition and an incrementation expression is in one line. The for loop executes commands or a block of statements repeatedly until a specified condition evaluates to false. A for loop is used when you know the number of iterations for executing the command.
Syntax of for loop
for (initialization ; condition ; incrementation) ;
{
message ;
}
Example
The example of for loop are as follows:
<?php
echo "The table of 2 is using for loop : ".'<br>';
for ($i=2;$i<=20;$i=$i+2)
{
echo $i.'<br>';
}
?>
Output
The foreach loop
The foreach loop is the same as a for loop but the difference is that there is no need for incrementing in a foreach loop. The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach loop is used when you don't know the number of iterations required.
Syntax of foreach loop
foreach ($array_var as $value)
{
message to be executed;
}
Example
The example of a foreach loop is as follows:
<?php
echo "The table of 2 is using foreach loop : ".'<br>';
$i=array(2,4,6,8,10,12,14,16,18,20);
foreach ($i as $value)
{
echo $value . "<br />";
}
?>
Output
Conclusion
So in this article you saw types of loops and how to use loops in PHP. Using this article one can easy understand looping in PHP.
Some Helpful Resources