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

If you want to jump out of the loop or terminate the loop when using foreach() in php, how to implement it

不言
Release: 2023-04-03 21:42:01
Original
8170 people have browsed 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
Copy after login

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

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!

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