For those programmers coming to PHP from other languages, the distinction between the keywords break and continue is quite clear. The former is used to abort loop execution or a switch statement while the latter is used to skip to the top (or bottom) of a loop.
So, despite knowing better, I still found myself spending more time than I’d like debugging the following code:
<?php
foreach ($daysOfTheWeek as $day)
{
switch (strtolower($day))
{
case 'monday':
case 'tuesday':
case 'wednesday':
case 'thursday':
case 'friday':
$this->processWeekdayData();
case 'saturday':
case 'sunday':
// nobody works on the weekend.
continue;
}
//
// this keeps getting thrown on saturday and sunday !!! how come?
//
throw new InvalidDayException('not a valid day');
}
?>
The problem?
The continue keyword in a switch statement does not work the same way as in other languages. In PHP, continue and break are synonymous inside this construct:
<?php
switch ($months)
{
// start with vowels
case 'august':
break;
case 'april':
continue; // exactly the same as "break" !!!
default:
return 'OK';
}
throw new StartsWithVowelException('Months with vowels are creepy');
?>
While we are on the topic, these two keywords have a feature in PHP that make them a bit more interesting and powerful than their peers in other languages.
Both can be given a numerical argument when used in a loop that indicates how many loops to continue through or break out of. For example, to abort two loops while in the inner loop:
<?php
//
// search through our 2D array until we find $value
//
$lowerval = strtolower($value);
foreach ($TwoDArray as $otherArray)
{
foreach ($otherArray as $value)
{
if (strtolower($value) == $lowerval)
{
// we found the value -- break out of both loops
break 2;
}
}
}
?>
Similarly, to restart the execution of an outer loop from within an inner one:
<?php
//
// verify that each sub array contains the given value
//
$lowerval = strtolower($value);
foreach ($TwoDArray as $otherArray)
{
foreach ($otherArray as $value)
{
if (strtolower($value) == $lowerval)
{
// we found the value -- this one definitely has it.
continue 2;
}
}
// if we've reached here, then the inner loop doesn't have the
// value. ¡aiiee!
}
?>
PHP has a few quirks that can make programmers from other languages scratch their heads, but you will quickly find that these are very easy to get used to and make the language the wonderfully productive one that it is.