The topic of break
and continue
came up the other day and I thought it would make for a good blog post. You’re probably familiar with break
moreso than continue
because it is part of a switch
statement’s syntax. Both break
and continue
can also be used inside of looping statements like while
, for
and foreach
. According to php.net continue
can also be used with switch
statements because it is also considered a looping structure.
When used inside of looping statements, break
and continue
serve similar yet different purposes. break
is for ending the loop indefinitely while continue
is used to skip the rest of the current iteration and move on to the next iteration.
Print only even numbers
for ($i = 1 $i <= 100 $i++)
{
if ($i % 2)
{
echo 'Even: ' . $i . "n"
}
else
{
continue
}
}
Find Bobby Fischer
$players = [
'The Turk',
'Paul Morphy',
'Mikhail Botvinnik',
'Deep Blue',
'Bobby Fischer',
'Alexander Alekhine',
foreach ($players as $player)
{
if ($player == 'Bobby Fischer')
{
echo 'Found him!'
break
}
}
You may have noticed that the continue
and break
were not really necessary in the examples above. If you did notice that, you would be correct! The truth is, you can usually write code without using continue
or break
just by writing a conditional statement (which you’d have to write anyway ;). break
can play an important role when looping through large datasets and want to ensure that it stops as soon as possible instead of looping through all of the data. At the same time, you can usually accomplish finding data in arrays by other less system intensive methods.
Both break
and continue
also accept a single, optional argument that tells it how many levels of loops to skip or break out of. The default is 1 to either skip the current iteration or current loop.