The following examples demonstrate Working With Loops in PHP.

The for Loop

Basically, a for loop is an entry-controlled loop. It means, the loop checks the condition before it begins executing any statement. Therefore, if the condition is not true, the control comes out of the loop.

The while Loop

In fact, the while loop is also entry-controlled loop. However, it contains separate statements for initialization, condition, and update of loop control variable.

do…while Loop

Unlike for loop and while loop, the do…while loop is an exit-controlled loop. Therefore, it checks the condition after executing loop statements.

<?php
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
echo '<h1>Example of Using Loops in PHP</h1>';
$n=12;
echo '<h2>Sum of first n numbers using for loop</h2>';
$sum=0;
for($i=1;$i<=$n;$i++)
{
    $sum+=$i;
}
echo '<h3>Sum of first '.$n.' numbers = '.$sum;
echo '<h2>Sum of first n numbers using while loop</h2>';
$n=20;
$sum=0;
$i=1;
while($i<=$n)
{
    $sum+=$i;
    $i++;
}
echo '<h3>Sum of first '.$n.' numbers = '.$sum;

echo '<h2>Sum of first n numbers using do...while loop</h2>';
$n=15;
$sum=0;
$i=1;
do
{
    $sum+=$i;
    $i++;
}while($i<=$n);
echo '<h3>Sum of first '.$n.' numbers = '.$sum;
echo '<h2>Display a series of '.$n.' terms using for loop</h2>';
$n=12;

for($i=1,$j=1;$i<=$n;$i++, $j=$i+$j)
{
    echo $j.' ';
}
echo '<h2>Display a series of '.$n.' terms using while loop</h2>';
$n=15;
$i=1;
$j=1;
while($i<=$n)
{
    echo $j.' ';
    $i++;
    $j=$i+$j;
}
echo '<h2>Display a series of '.$n.' terms using do...while loop</h2>';
$n=20;
$i=1;
$j=1;
do
{
    echo $j.' ';
    $i++;
    $j=$i+$j;
}while($i<=$n);

echo '<h2>Using break and continue with for loop</h2>';
$n=12;
for($i=1,$j=1;$i<=$n;$i++, $j=$i+$j)
{
    if($j%5==0) continue;
    if($j%13==0) break;
    echo $j.' ';
}
?>

Output

Examples of Working With Loops in PHP
Examples of Working With Loops in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

PHP Practice Questions