5
When I want to interrupt a loop of one for
, while
or foreach
always use the break;
within a if
with the following structure:
$teste = array(1,2,3,4,5);
foreach($teste as $t){
if($t == 3){
echo "Terminando loop ao achar o número ".$t;
break;
}
echo $t."<br />";
}
echo "fim de script";
We can use the continue:
foreach($teste as $t){
if($t == 3){
echo "O ".$t." é meu!";
continue;
}
echo $t."<br />";
}
echo "fim de script";
In the manual, there’s this:
Note that in PHP the switch is considered a loop structure for purposes of the continue.
But if you want the switch
instead of if
, and stop the structure foreach
when a particular occurrence is found?
it is possible to use the continue
for some purposes or the break
to interrupt the loop of foreach
making use of the switch
?
I didn’t know that
02
within thebreak
that’s what it was for! Thanks.– Cassiano José
I didn’t know this either, I just thought parentheses were unnecessary
()
, but does not invalidate the answer. + 1– Guilherme Nascimento