break out of if and foreach

后端 未结 4 1895
鱼传尺愫
鱼传尺愫 2020-11-30 17:43

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_de         


        
4条回答
  •  半阙折子戏
    2020-11-30 18:29

    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;
    

提交回复
热议问题