Heim  >  Fragen und Antworten  >  Hauptteil

Brechen von if und foreach

<p>Ich habe eine foreach-Schleife und eine if-Anweisung. Ich muss endlich aus dem foreach ausbrechen, wenn eine Übereinstimmung gefunden wird. </p> <pre class="brush:php;toolbar:false;">foreach ($equipxml as $equip) { $current_device = $equip->xpath("name"); if ($current_device[0] == $device) { // Eine Übereinstimmung in der Datei gefunden. $nodeid = $equip->id; <hier aus if und foreach ausbrechen> } }</pre> <p><br /></p>
P粉651109397P粉651109397390 Tage vor533

Antworte allen(2)Ich werde antworten

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

    只需使用break。这样就可以了。

    Antwort
    0
  • P粉729436537

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

    if 不是循环结构,因此您无法“打破它”。

    但是,您可以通过简单地调用 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 "!";

    结果输出:

    Antwort
    0
  • StornierenAntwort