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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
// This will end the loop after five cycles
for($i = 0; $i < 10; $i += 1)
{
	echo $i;
	
	if($i >= 5)
	{
		break;
	}
}

Foreach loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
$i = 0;

// This will end the loop after the counter reaches 5
while(true)
{
	echo $i;
	
	if($i >= 5)
	{
		break;
	}
}

Do-while loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
$i = 0;

// This will end the loop after the counter reaches 5
do
{
	echo $i;
	
	if($i >= 5)
	{
		break;
	}
}
while(true);

Switch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?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;
}