How to stop a loop PHP

2020-05-09 17:46发布

I'm trying to figure out if its possible to stop a foreach loop in PHP, like this,

$arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
$i=0;
foreach($arr as $val){
    echo $val;
    if($i == 2){
         //Stop looping
    }
}

Is there anyway how to do that, if yes how do I that?

Thank you.

4条回答
小情绪 Triste *
2楼-- · 2020-05-09 18:20

You can break out of a loop with break.

查看更多
地球回转人心会变
3楼-- · 2020-05-09 18:23

Use break and increment $i.

$arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
$i=0;
foreach($arr as $val){
    echo $val;
    if(++$i == 2){
       break; 
   }
}
查看更多
家丑人穷心不美
4楼-- · 2020-05-09 18:29

You can use good old keyword break here as well. Followed by a semicolon ; of course.

if($i == 2){
     break;
}

Manual for break

查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-09 18:34

1)As said earlier u need to increment the loop. 2)...if ur using multiple "foreach" that are nested,you can do break 'n' to get out of n nested loop,where n will specify any number from 1 to the total number of loops that you have used.Hope it helps!

查看更多
登录 后发表回答