Home  >  Article  >  Backend Development  >  How to stop looping in php foreach

How to stop looping in php foreach

藏色散人
藏色散人Original
2021-07-17 10:51:337854browse

php How to stop the foreach loop: 1. Jump out of the foreach loop through continue; 2. Terminate the foreach loop through break.

How to stop looping in php foreach

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to stop the loop of php foreach?

Foreach jumps out of this/current loop and terminates the loop method

In the foreach() loop, you want to jump out of this loop when a certain condition is met. Continue to execute the next loop, or terminate the foreach() loop when a certain condition is met. You will use: continue and break respectively

PHP:

 foreach($arras $key => $value){  
    if($value=='b'){
        $html.= $value;  
        continue;// 当 $value为b时,跳出本次循环  
    }  
    if($value=='c'){  
        $html.= $value;  
        break;// 当 $value为c时,终止循环  
    }
}
echo$html; // 输出: abc

JavaScript:

var myerror = null;  
             try{  
                 arr.forEach(function(el,index){  
                     if (el==20) {  
                         console.log("try中遇到20,能退出吗?");//  
                         foreach.break=new Error("StopIteration");  
                     }else{  
                         console.log(el);  
                     }  
                 });  
             }catch(e){  
                 console.log(e.message);  
                 if(e.message==="foreach is not defined") {  
                     console.log("跳出来了?");//  
                     return;  
                 }else throw e;  
             }//可以跳出来

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to stop looping in php foreach. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn