Should I ever use continue inside a switch statement?
The documentation for the PHP continue
statement makes this clear:
Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
You should know that different languages give the same keywords subtly different meanings, and not assume that PHP continue
behaves the same as C++ continue
.
If continue
makes sense in a PHP switch
where it wouldn't work in C++, do use it.
If continue
makes sense in a C++ switch
where it wouldn't work in PHP, do use it.
As is warned in the PHP Manual:
"Note that in PHP the switch statement is considered a looping structure for the purposes of continue."
So the use of continue will break out of the switch statement, not the for loop. The perils of assuming similar syntax across languages.
Try using continue 2
to continue to the next iteration of the loop surrounding the switch statement.
EDIT:
$foo = 'Hello';
for ($p = 0; $p < 8; $p++) {
switch($p) {
case 3:
if ($foo === 'Hello') {
echo $foo;
break;
} else {
continue 2;
}
default:
echo "Sleeping...<br>";
continue 2;
}
echo "World!";
break;
}
//This will print:
Sleeping...
Sleeping...
Sleeping...
Hello World!
PHP 7.3 or newer:
Using continue
to break a switch
statement is deprecated and will trigger a warning.
To exit a switch
statement, use break
.
To continue to the next iteration of a loop that's surrounding the current switch
statement, use continue 2
.
PHP 7.2 or older:
continue
and break
may be used interchangeably in PHP's switch
statements.