break out of if and foreach

2019-01-12 17:50发布

问题:

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the 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>
    }       
}

回答1:

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

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();
}

Just for completeness for others that stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

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

Resulting output:

1 3 2 1 !


If - for some obscure reason - you want to break out of an if statement (which is not a loop structure and thus not breakable per definition), you can simply wrap your if in a tiny loop structure so you can jump out of that code block.

Please note that this is a total hack and normally you would not want to do this:

do if ($foo)
{
  // Do something first...

  // Shall we continue with this block, or exit now?
  if ($abort === true) break;

  // Continue doing something...

} while (false);

The example above is taken from a comment in the PHP docs

If you wonder about the syntax: It works because an abbreviated syntax is used here. The outer curly braces can be left out because the loop structure contains only a single statement: if ($foo) { .. }.

Another example for this:
do $i++; while ($i < 100) is equivalent to do { $i++; } while ($i < 100).



回答2:

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

Simply use break. That will do it.



回答3:

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

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


回答4:

For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or 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);
    }
}

?>

If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here