Home >Backend Development >PHP Tutorial >If you want to jump out of the loop or terminate the loop when using foreach() in php, how to implement it
The content of this article is about the implementation method of jumping out of the loop or terminating the loop when using foreach() in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
Example 1:
When using foreach() in a loop in PHP, I want to
$arr = array('a','b','c','d','e'); $html = ''; foreach($arr as $key => $value){ if($value=='b'){ $html .= $value; continue; // 当 $value为b时,跳出本次循环 } if($value=='c'){ $html .= $value; break; // 当 $value为c时,终止循环 } $html .= $value; } echo $html; // 输出: ab
want to jump out of this loop when a certain condition is met. The loop continues to execute the next loop, or when a certain condition is met, the foreach() loop is terminated. Continue and break are used respectively.
Example 2:
<?php $array = array(1,2,3,4,5,6,7,8,9); foreach ($array as $value) { echo $value; if ($value == 5) { break; } } ?> 结果:12345
Related recommendations:
php method to achieve infinite classification: recursive method and reference method
Simple difference comparison and usage introduction between Public&Private&Protect in php
The above is the detailed content of If you want to jump out of the loop or terminate the loop when using foreach() in php, how to implement it. For more information, please follow other related articles on the PHP Chinese website!