I used some coding for learn break and continue statement. The break statement working fine but continue statement not working. I will give my codeing
<?php
for($a=1; $a<=10; $a++){
echo $a;
echo "<br>";
if($a==6){
break;
}
else{
continue;
}
}
Because in your for
loop, continue
is the last statement so, nothing is available to skip, as it will automatically go to beginning of the next iteration.
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration
break ends execution of the current for, foreach, while, do-while or switch structure.
for($a=1; $a<=10; $a++){<--------------------┐
|
echo $a; |
echo "<br>"; |
if($a==6){ |
break; ----- jumps here ------┐ |
} | |
| |
Remove else `continue` here,it will go | |
to the beginning automatically until | |
loop fails -----------------------------------┘
|
} |
<--------------------┘
AS PER COMMENT:
<?php
for($a=1; $a<=10; $a++){
echo $a;
echo "<br>";
if($a==6){
break;
}
else{
echo "before continue <br/>";
continue;
echo "after continue <br/>"; // this will not execute because continue goes beginning of the next iteration
}
}
continue
means "skip the rest of the loop and go back to the top of the loop", since your continue
is the last thing in your loop, there is nothing to skip, so the same thing will happen whether or not the continue
is there.
Your variable doesn't hit the continue
statement. Look at this example:
$i = 10;
while (--$i)
{
if ($i == 8)
{
continue;
}
if ($i == 5)
{
break;
}
echo $i . "
";
}
The output will be:
9 7 6