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

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。这样就行了。

如果不是一个循环结构,那么你就不能“跳出来”。

但是,您可以通过简单地调用break来跳出foreach。在你的例子中,它达到了预期的效果:

$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 "!";

输出结果:

One, three, two, one!

在PHP中打破foreach或while循环的更安全的方法是在原始循环中嵌套一个递增的计数器变量和if条件。这给你更严格的控制比打破;这可能会对复杂页面的其他地方造成破坏。

例子:

// 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;

对于那些在这里搜索如何跳出包含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将返回此错误:不能中断/继续一级。我在这里找到了更多细节