程序是从上向下依次执行,执行过的不能跳调回去,也不能跳过一些代码片段执行。有了goto操作符可以用来跳转到程序中的另一位置。该目标位置可以用目标名称加上冒号来标记,而跳转指令是 goto 之后接上目标位置的标记。
break是结束整个循环体,continue是结束单次循环
break num是结束外层第num层整个循环体,continue num 是结束外层第num层单次循环
<?php
$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;
}
}
goto语句使用
goto的使用一直有争议[5.3版本增加]
支持者:goto使用起来比较灵活,而且有些情形能提高程序的效率。
反对者:goto语句使程序的静态结构和动态结构不一致,使程序难以理解、难以查错。
PHP 中的 goto 有一定限制,目标位置只能位于同一个文件和作用域,也就是说无法跳出一个函数或类方法,也无法跳入到另一个函数。也无法跳入到任何循环或者 switch 结构中。可以跳出循环或者 switch,通常的用法是用 goto 代替多层的 break
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
以上例程会输出:Bar
for ($i = 0, $j = 50; $i < 100; $i++) {
while ($j--) {
if ($j == 17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
以上例程会输出:j hit 17
比如sql中where条件中的1 and需要去除 但不能判断使用的次数
// $where = '1 and 1 and user_id=40';
// remove_1and:
// if (starts_with($where, "1 and")) {
// $where = substr($where, 6);
// goto remove_1and;
// }
$where = preg_replace("/\s(?=\s)/", "\\1", $where);
while (starts_with($where, "1 and")){
$where = substr($where, 6);
}
能用其他方式替换goto的尽量用其他方式