Signup/Sign In

PHP break statement

We have already seen and used break statements in the switchswitch conditional statements.

To recall, in switch code blocks, we used break statement to break out of the switch block when a valid case block gets executed.

Let's see an example for simple switch code:

<?php

$a = 1;

switch($a)
{
    case 1:
        echo "This is case 1";
        break;
    case 2:
        echo "This is case 2";
        break;
    default:
        echo "This is default case";
}

?>

This is case 1


But what if we forget to add the break statement at the end of each case block in the switch statement? In that case, the execution will still start from the matching case, but will not exit out of the switch statement and will keep on executing every code statement below it until the next break statement.

<?php

$a = 2;

switch($a)
{
    case 1:
        echo "This is case 1";
    case 2:
        echo "This is case 2";
    default:
        echo "This is default case";
}

?>

This is case 2 This is default case


Using break in Loops

In Loops, the break statement is very useful for situations when you want to exit out of the loop(stop the loop), if some condition is satisfied.

Let's take a simple example of a for loop to understand how we can use break statement in loops.

In the example below, we want to find the first number divisible by 13, which is between 1762 and 1800, starting from 1762.

<?php

$x = 13;

for($i = 1762; $i < 1800; $i++)
{
    if($i % $x == 0) 
    {
        echo "The number is $i";
        break;
    }
}

?>

The number is 1768

In the above script, we start our for loop from 1762, and run it till 1800. In every iteration/cycle, we check whether the incremented number is divisible by 13. When we find the first number for which the remainder is 0, we exit from the loop using the break statement.

The usage of break statement is same for all the different types of loops.