简体   繁体   中英

break if statement and continue loop

how to break a if statement in foreach and continue loop? i used break; but it closing the loop too:(

 foreach($arry as $s){
        
        if(trim($row['img1']) == ''){
            $insrt="UPDATE testt SET img1=:img1";
            $r=$connect->prepare($insrt);
            $r->bindparam(":img1",$s);
            $r->execute();
            echo"$s";
            break;
        }elseif(trim($row['img2']) == ''){  
            $insrt="UPDATE testt SET img2=:img2";
            $r=$connect->prepare($insrt);
            $r->bindparam(":img2",$s);
            $r->execute();
            echo"$s";
            break;
        }

@Nigel Ren already commented what I was going to say but I'm adding it as an answer anyway. If statements don't need a break or continue . Look at this example:

foreach(...) {
  if(condition) {
    //will work only if the condition is true
  } else {
    //will work if the condition is not true
  }

  //will always work (after if-else block) as long as the loop continues
}

You only break when you really want to stop the loop.

In your case I'm guessing you want to loop until the end so no break is needed.

You can use a break when you get invalid if/elseif.

So you could put a continue in your if and in your elseif statement and a break after the last elseif (outside of the if elseif statements)

foreach($arry as $s){
    
    if(trim($row['img1']) == ''){
        $insrt="UPDATE testt SET img1=:img1";
        $r=$connect->prepare($insrt);
        $r->bindparam(":img1",$s);
        $r->execute();
        echo"$s";
        continue;
    }elseif(trim($row['img2']) == ''){  
        $insrt="UPDATE testt SET img2=:img2";
        $r=$connect->prepare($insrt);
        $r->bindparam(":img2",$s);
        $r->execute();
        echo"$s";
        continue;
    } 
break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM