Breaking if and foreach
P粉651109397
P粉651109397 2023-08-28 11:32:39
0
2
599
<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粉651109397
P粉651109397

reply all(2)
P粉564192131
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.

P粉729436537

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template