1. While Loop in PHP :

Syntax :

while(expression)
{
        Statements to be executed;
}

It executed the nested statements repeatedly as long as the while expression evaluates to TRUE.

The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement execution will not stop until the end of the iteration.

Example :
<?php
$A = 1;
while($A <= 3)
{
echo “<br>” , $A++;
}
?>

While Loop in PHP

 2. do while Loop in PHP :

do while loops are very similar to while loops, except the truth expression is checked at the end of every iteration instead of the beginning.

The main difference between do while loop and while loop is that the first iteration of do while loop is guaranteed to run whereas it’s may not necessarily run with a while loop.

This loop would run one atleast one time as expression is checked after the first iteration.

Syntax :

do
{
       Statements to be executed;

} while(expression);

Example :
<?php
$A = 4;
do
{
echo $A- -, “<br>”;
}while($A >0)
?>

Do While Loop in PHP

3.For Loop in PHP:

Syntax :

for(expression-1; expression -2  ; expression -3)
{
      Statements to be executed;
}

First expression is evaluated once unconditionally at the beginning of the loop. In first expression assignment is done.

In the beginning of each iteration, expression 2 is evaluated. It true then loop continues and nested statements are executed. IF false, the execution of the loop ends. If this expression left empty means loop will execute infinitely.

At the end of each iteration, expression -3 is evaluated.

Example :
<?php
echo “Example : 1 <br>”;
for($A=5 ;$A<=9 ; $A++)
{
echo ”    ” ,$A;
}

echo “<br><br>Example : 2 <br>”;
for($B=2 ;; $B++)
{
if($B > 6)
{  break;
}
echo ”    “, $B;
}

echo “<br><br>Example : 3 <br>”;
$C=2;
for(;;)
{
if($C > 10)
{
break;
}
echo ”    “, $C;
$C+=2;
}
?>

 

FOR Loop in PHP

4. foreach Loop in PHP:

foreach loop is used in array only and execute each vale of an array.With each iteration array pointer is increase by one.

Syntax :

foreach (array as value)
{
     Statements to be executed;
}

Example :
<?php
$arr=array(“A”, “B”,”C”);
foreach($arr as $val)
{
echo “<br>” ,$val;
}
?>

Foreach Loop in PHP

5. Break in PHP in PHP:

Break ends the execution of loop i.e. it exists from the innermost loop construct that contains it.

Example :
<?php
for($A=1 ;$A<=5 ; $A++)
{
if($A > 3)
break;
echo “<br>” ,$A;
}
?>

Break in PHP

6. Continue in PHP :

Continue skips the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Example :
<?php
for($A=1 ;$A<=5 ; $A++)
{
if($A == 2)
continue;
echo “<br>” ,$A;
}
?>

Continue in PHP

Difference between Break and Continue