突破 if 和 foreach

新手上路,请多包涵

我有一个 foreach 循环和一个 if 语句。如果找到匹配项,我需要最终摆脱 foreach。

 foreach ($equipxml as $equip) {

    $current_device = $equip->xpath("name");
    if ($current_device[0] == $device) {

        // Found a match in the file.
        $nodeid = $equip->id;

        <break out of if and foreach here>
    }
}

原文由 au_stan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 346
2 个回答

if 不是循环结构,所以你不能“摆脱它”。

但是,您可以通过简单地调用 --- 来突破 foreach break 。在您的示例中,它具有预期的效果:

 $device = "wanted";
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file
        $nodeid = $equip->id;

        // will leave the foreach loop immediately and also the if statement
        break;
        some_function(); // never reached!
    }
    another_function();  // not executed after match/break
}


只是为了其他偶然发现这个问题并寻找答案的人的完整性。

break 接受一个可选参数,它定义了它应该中断 多少 个循环结构。例子:

 foreach (['1','2','3'] as $a) {
    echo "$a ";
    foreach (['3','2','1'] as $b) {
        echo "$b ";
        if ($a == $b) {
            break 2;  // this will break both foreach loops
        }
    }
    echo ". ";  // never reached!
}
echo "!";

结果输出:

1 3 2 1 !

原文由 Kaii 发布,翻译遵循 CC BY-SA 4.0 许可协议

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file
        $nodeid = $equip->id;
        break;
    }
}

只需使用 break 。这样就可以了。

原文由 Decent Dabbler 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题