Home » Tutorials » PHP » Break and Continue

Break and Continue

While not used very often in PHP, continue and break deserve much more credit. Continue and break provide extra control over your loops by manipulating the flow of the iterations. 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. Break provides more aggressive control by completing skipping out of the loop and onto the code following the loop. If you have ever played the card game UNO, continue is basically the skip card, and break is someone slamming their cards down screaming I am the winner and leaves the room. Let’s go through some examples to see how to use them.

Example
$i = 0;
for ($i = 0;$i <= 5;$i++)
{
    if ($i==2)
    {
        break;
    }
    echo $i;
    echo "<br />";
}
echo "End of for loop" ;
Result 0
1
End of for loop

Once the var $i reaches 2 in the for loop, it meets the conditional statement $i == 2, which is then executed. The statement executed is break;. When break is executed it actually breaks us out of the for loop, which is why when $i equals 2 we exit the for loop and execute echo “End of for loop”; instead of ending the for loop when $i equals 5. Remember break escapes the entire logic of the other iterations.

Example
$i = 0;
for ($i = 0;$i <= 5;$i++)
{
    if ($i==2)
    {
        continue;
    }
    echo $i;
    echo "<br />";
}
echo "End of for loop" ;
Result 0
1
3
4
5
End of for loop

It seems pretty obvious that continue is different than break. Notice how the only result not printed is 2. The continue basically says let’s skip out of this particular instance of the loop and move onto the next one. When we are running through the instance where $i becomes equal to 2, we meet the conditional statement if( $i == 2) where it is true. Then, we execute the continue, which stops us from executing the following statements in the loop. We then run through the next iteration of the loop where $i equals 3. Since we don’t meet the conditional statement this time, we write the following statements and will never enter into conditional if($i == 2).



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Break and Continue". After Hours Programming. Accessed on April 23, 2024. https://www.afterhoursprogramming.com/tutorial/php/break-and-continue/.

  • Stewart, Suzy. "Break and Continue". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/php/break-and-continue/. Accessed 23 April, 2024.

  • Stewart, Suzy. Break and Continue. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/php/break-and-continue/.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.