Home  >  Q&A  >  body text

Breaking if and foreach

<p>I have a foreach loop and an if statement. I need to finally break out of the foreach if a match is found. </p> <pre class="brush:php;toolbar:false;">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> } }</pre> <p><br /></p>
P粉651109397P粉651109397441 days ago589

reply all(2)I'll reply

  • P粉564192131

    P粉5641921312023-08-29 09:28:59

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

    Just use break. that's it.

    reply
    0
  • P粉729436537

    P粉7294365372023-08-29 00:47:33

    if is not a loop structure, so you can't "break it".

    However, you can break out of foreach by simply calling break. In your example it has the expected effect:

    $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
    }

    Just to keep it intact for anyone else who stumbles across this question and is looking for an answer.

    break Takes optional arguments defining how many loop structures it should break. Example:

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

    Result output:

    reply
    0
  • Cancelreply