Home /PHP/Break and Continue

Break and Continue

While not used very often in PHP, continue and break deserve much more credit. These 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 completely skipping out of the loop and moving to the code following the loop.

If you’ve ever played the card game UNO, continue is like the skip card, while break is someone slamming their cards down screaming, “I am the winner!” and leaving 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 variable $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 exits the for loop entirely, which is why when $i equals 2, we move to the statement echo "End of for loop"; instead of finishing the loop when $i equals 5. Remember, break escapes the entire logic of the remaining 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’s clear that continue is different from break. Notice how the only result not printed is 2. The continue basically says, “Let’s skip this particular instance of the loop and move to the next one.” When $i becomes equal to 2, we meet the conditional statement if($i == 2), which evaluates to true. Then, we execute continue, which stops the following statements in the loop from being executed. The loop then proceeds to the next iteration where $i equals 3. Since the condition is not met, the following statements are executed, and the conditional if($i == 2) is never entered again.