How to stop looping in php foreach

藏色散人
Release: 2023-03-11 16:56:01
Original
7859 people have browsed it

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
Copy after login

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;  
             }//可以跳出来
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template