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.
You can break out of a loop with
break
.Use
break
and increment$i
.You can use good old keyword
break
here as well. Followed by a semicolon;
of course.Manual for
break
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!