PHP “continue” statement is used within the loops to skip the current loop iteration and goes to the next iteration.
See the syntax structure of “continue statement”
while ( expression 1)
{
if ( expression 2 )
{
continue ;
}
// Operation Statements
}
In this structure if expression 2 return TRUE , continue statement will execute and it will skip that iteration and wont execute the rest portions of code after the “continue” command, control will go to the next iteration in while loop with expression 1.
See the sample PHP program with “continue” statement
<?php $a = 0; while ( $a < 3) { $a++; $b = 0; while ( $b < 5) { $b++; if ($b==3) { continue; } echo $a*$b." "; } echo "<br>"; } ?>
Output of this program will be
1 2 4 5
2 4 8 10
3 6 12 15
We can see that it skipped the third records in each loop.
We can use optional parameter with continue statement for specifying how many levels of loops ( not iteration ) should be skipped.
See the following continue syntax structure
while ( expression 1)
{
while ( expression 2 )
{
if ( expression 3 )
{
continue 2;
}
// Operation Statements
}
}
In this structure , if expression 3 becomes TRUE , continue statement will execute with parameter 2. So it will skip the current iteration in while loop with expression 2 also with current iteration with first while loop with expression 1. Next iteration will start from the first while loop.
See the sample php program with continue statement with parameter
<?php $a = 0; while ( $a < 3) { $a++; $b = 0; while ( $b < 5) { $b++; if ($b==3) { continue 2; } echo $a*$b." "; } echo "<br>"; } ?>
Output of this program will be
1 2 2 4 3 6
Here we can see that when $b == 3 , control goes to the first while loop with next iteration. Due to the skipping of rest codes line break statement ( echo “<br>”; ) also wont execute.
Note : Difference between Continue and break statement is that
- Break statement skip the current loop and control will come out from the current loop structure
- Continue statement skip the current iteration only, control will goes to the next loop iteration
Do a check the programs with break statement in PHP