Home > Article > Backend Development > php--break/continue
break
(PHP 4, PHP 5)
break ends the execution of the current for, foreach, while, do-while or switch structure.
break can accept an optional numeric parameter to determine how many loops to break out of.
<?php $arr = array('one', 'two', 'three', 'four', 'stop', 'five'); while (list (, $val) = each($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br />\n"; } /* 使用可选参数 */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* 只退出 switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* 退出 switch 和 while 循环 */ default: break; } } ?>
continue
(PHP 4, PHP 5)
continue is used in the loop structure to skip the remaining code in this loop and start executing the next loop when the condition evaluates to true.
Note: Note that in PHP the switch statement is considered a loop structure that can use continue.
continue accepts an optional numeric parameter to determine how many loops to skip to the end of the loop. The default value is 1, which jumps to the end of the current loop.
<?php while (list ($key, $value) = each($arr)) { if (!($key % 2)) { // skip odd members continue; } do_something_odd($value); } $i = 0; while ($i++ < 5) { echo "Outer<br />\n"; while (1) { echo "Middle<br />\n"; while (1) { echo "Inner<br />\n"; continue 3; } echo "This never gets output.<br />\n"; } echo "Neither does this.<br />\n"; } ?>
Omitting the semicolon after continue can lead to confusion. The following example shows how this should not be done.
<?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?>
The desired result is:
0 1 3 4
But the actual output is:
2
Because the entire continue print "$in"; is evaluated as a single expression, so the print function only works when $i == 2 It is called only when it is true (the value of print is passed to continue as the optional numeric parameter mentioned above).