Break & Continue

Continue and break provide extra control over your loops by manipulating the flow of the iterations.


Break :

  • Break ends a loop completely
  • Break provides more aggressive control by completing skipping out of the loop and onto the code following the loop 
  •  

 Continue
  • Just shortcuts the current iteration and moves on to the next iteration
  • Continue is the nicer one of the two as it prevents the current iteration, or flow through one pass of the loop, and just tells PHP to go to the next round of the loop.



Example :

<?php
$i = 0;
for ($i = 0;$i <= 5;$i++)
{

    if ($i==2)
    {

        break;

    } echo $i;
    echo "<br />";

}
echo "End of for loop" ;
?>

Output :

0
1
End of for loop 

$i = 0;
for ($i = 0;$i <= 5;$i++)
{

    if ($i==2)
    {

        continue;

    }
    echo $i;
    echo "<br />";

}
echo "End of for loop" ;

Output :

0
1
3
4
5
End of for loop 

Comments