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.
Use break
and increment $i
.
$arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
$i=0;
foreach($arr as $val){
echo $val;
if(++$i == 2){
break;
}
}
You can use good old keyword break
here as well. Followed by a semicolon ;
of course.
if($i == 2){
break;
}
Manual for break
You can break out of a loop with 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!