Home > Article > Backend Development > How to stop looping in php foreach
php How to stop the foreach loop: 1. Jump out of the foreach loop through continue; 2. Terminate the foreach loop through break.
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!