PHP 中的突破级别
我有这段代码,它工作得很好(因为在我的示例中,该变量确实存在于 $arrival_time 中,因此它在大约 $k = 10 处中断)。
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break;
}
}
是不是和这段代码是一样的?我添加了 while(true) 循环并增加了“中断级别” - 所以现在是 break 2,而不仅仅是 break。但似乎这是一个无限循环。为什么?
while (true) {
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break 2;
}
}
}
为什么要添加while(true)?因为我需要定义更多语句(这里不需要解释),如果 while 循环内找不到匹配的语句(如果第一种情况下的“break”,第二种情况下的“break 2”不运行)。
无论如何 - 为什么这不起作用?
I have this snippet of code and it's working just fine (because in my example that variable really exists in $arrival_time so it breaks at about $k = 10).
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break;
}
}
Isn't that the same as this code? I added the while(true) loop and increased the "break level" - so it's now break 2, not just break. But seems that's an infinite loop. Why?
while (true) {
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break 2;
}
}
}
Why adding while(true)? Because I need to define some more statements (which here aren't neccesary for explanation) if inside while loop doesn't find the matching one (if that "break" in first case, "break 2" in second case doesn't run).
Anyway - why this isn't working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在某些情况下,内部 while 循环的谓词永远不会被命中,因此 while 循环永远不会被执行。由于之后没有休息,因此循环将永远运行。这种情况是如果数组为空,
0
0
0
0
0
0
0
0
为假。从
$k = -1
开始,第一次计算谓词时,当您使用预自增运算符时,$k
将为0
,对于空数组,这将计算为 false 并且代码无限运行。如果没有while(true)
循环,这不会导致任何问题,因为您只需直接跳过它即可。In some cases, the predicate for the inner while loop is never hit, thus the while loop is never executed. As you don't have a break after it, the loop will run forever. This case would be if the array is empty,
0 < 0
is false.Starting with
$k = -1
, the first time the predicate gets evaluated,$k
will be0
as you are using the preincrement operator, for an empty array this will evaluate to false and the code with run infinite. Without thewhile(true)
loop this wouldn't cause any problems as you'd just jump straight over it.