break ends a loop right away, even if the loop condition is still true.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i === 4) {
break;
}
echo $i . " ";
}
echo "\nStopped at $i";
1 2 3
Stopped at 4
When $i reached 4, break jumped out of the loop. The code after the loop continues normally.
Find the first match
break is perfect for searching. Once you find what you need, there is no reason to keep looking.
<?php
$users = ["Asha", "Ben", "Chitra", "Dev"];
$found = null;
foreach ($users as $user) {
if (str_starts_with($user, "C")) {
$found = $user;
break;
}
}
echo $found ?? "Nobody found";
Chitra
break in a while loop
<?php
$total = 0;
while (true) {
$total += 25;
if ($total >= 100) {
break;
}
}
echo $total;
100
while (true) loops forever, so the only way out is break (or return). This is a valid pattern when the stop condition is easier to write in the middle of the loop.
Breaking out of nested loops
By default, break leaves only the loop it is in. Give it a number to leave more levels.
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
if ($row * $col === 4) {
echo "Found at row $row, column $col";
break 2; // leave both loops
}
}
}
Found at row 2, column 2
Inside a switch
break is also how switch cases end. A break inside a switch that sits in a loop only leaves the switch, not the loop.
Alternatives
In a function, return ends the loop and the function in one go. That is often cleaner than break.
<?php
function firstEven(array $numbers): ?int
{
foreach ($numbers as $n) {
if ($n % 2 === 0) {
return $n;
}
}
return null;
}
echo firstEven([3, 7, 8, 10]);
8
Prefer return in functions
return it as soon as you have it.