PHP 中的突破级别

发布于 2024-10-17 22:51:19 字数 918 浏览 4 评论 0原文

我有这段代码,它工作得很好(因为在我的示例中,该变量确实存在于 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天煞孤星 2024-10-24 22:51:19

在某些情况下,内部 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 be 0 as you are using the preincrement operator, for an empty array this will evaluate to false and the code with run infinite. Without the while(true) loop this wouldn't cause any problems as you'd just jump straight over it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文