打破if和foreach

时间:2012-02-09 17:19:36

标签: php if-statement foreach break

我有一个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>
    }       
}

4 个答案:

答案 0 :(得分:547)

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

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

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 and also the if statement
        break;
    }
    this_command_is_not_executed_after_a_match_is_found();
}

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

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

foreach (array('1','2','3') as $a) {
    echo "$a ";
    foreach (array('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!


如果 - 出于某些不明原因 - 你希望break出一个if语句(这不是一个循环结构,因此每个定义都不易破解),你可以简单地包装{{1在一个微小的循环结构中,你可以跳出那个代码块。

请注意,这是完全黑客攻击,通常你不想这样做:

if

以上示例取自comment in the PHP docs

如果您想知道语法:它的工作原理是因为这里使用了缩写语法。外部花括号可以省略,因为循环结构只包含一个语句:do if ($foo) { // Do something first... // Shall we continue with this block, or exit now? if ($abort === true) break; // Continue doing something... } while (false);

另一个例子:
if ($foo) { .. }相当于do $i++; while ($i < 100)

答案 1 :(得分:11)

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即可。那样做。

答案 2 :(得分:2)

在PHP中破解foreachwhile循环的一种更安全的方法是在原始循环内嵌套递增计数器变量和if条件。这使您可以比break;更严格地控​​制,这可能会导致复杂页面上的其他地方造成严重破坏。

示例:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ) 
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;

答案 3 :(得分:0)

对于那些登陆此处但是搜索如何打破包含include语句的循环的人,请使用return而不是break或continue。

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

如果你想在do_this_for_even.php里面打破,你需要使用return。使用break或continue将返回此错误:无法中断/继续1级。我找到了更多详细信息here