phpif-statementforeachbreak

break out of if and foreach


I have a foreach loop and an if statement. If a match is found I need to ultimately break out of that foreach and if.

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

Solution

  • 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:

    $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 for completeness for others who stumble upon this question looking for an answer..

    break takes an optional argument, which defines 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 "!";
    

    Resulting output:

    1 3 2 1 !