PHP Keywords: break

15 February 2019 - 9:53pm

Welcome to my series on every PHP keyword and its usage. Today's item: break.

The break statement is used within loops to break out of the current loop, and switches to end the current branch.

It also accepts an optional parameter that indicates how many layers of loop/switch it should break through. Hopefully you won't need to use this very often, as nested loops can be difficult to understand.

Usage

For loop

<?php
// This will end the loop after five cycles
for($i = 0; $i < 10; $i += 1)
{
    echo $i;

    if($i >= 5)
    {
        break;
    }
}

Foreach loop

<?php
$colours = ["red", "green", "blue", "yellow", "orange"];

// This will end the loop after it reaches "blue".
foreach($colours as $colour)
{
    echo $colour;

    if($colour === "blue")
    {
        break;
    }
}

While loop

<?php
$i = 0;

// This will end the loop after the counter reaches 5
while(true)
{
    echo $i;

    if($i >= 5)
    {
        break;
    }
}

Do-while loop

<?php
$i = 0;

// This will end the loop after the counter reaches 5
do
{
    echo $i;

    if($i >= 5)
    {
        break;
    }
}
while(true);

Switch

<?php
$colour = "red";

switch($colour)
{
    // Matches against blue
    case "blue":
        echo "Violets";
    break;

    // Matches against red or white, as there is no break statement
    // between red and white
    case "red":
    case "white":
        echo "Roses";
    break;

    default:
        echo "Unknown flowers";
    break;
}

Multiple loops

<?php
$i = 0;

// This will end both loops after both counters reach 5
while(true)
{
    for($j = 0; $j < 10; $j += 1)
    {
        echo $i, ",", $j;

        if($i >= 5 && $j >= 5)
        {
            // Break out of both statements
            break(2);
        }
    }

    $i += 1;
}