How to stop a loop PHP

2020-05-09 18:11发布

问题:

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.

回答1:

Use break and increment $i.

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


回答2:

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

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

Manual for break



回答3:

You can break out of a loop with break.



回答4:

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!