break and continue are two of the most commonly used sentences in PHP to manipulate the flow of iterations in cyclical control structures (for, foreach, while, do-while or switch). Both cut the current cycle but with an important difference:
break completes the execution of the control structure in progress.
continue completes the current iteration of the control structure and starts a new iteration.
while ( $foo ) { <--------------------┐
continue; --- vuelve aquí -----┘
break; ----- salta aquí ----┐
}
<---------------------┘
This implies, basically that:
In other words, continue tells PHP that the current iteration is over and should start in the evaluation of the condition that opens the control structure. For its part, break tells PHP that the evaluation of the current control structure is over and that it does not continue iterating.
If we do a simple test like this:
$letters = [ 'A', 'B', 'C' ];
foreach ( $letters as $letter) {
if( 'A' == $letter ) {
continue;
echo 'Esto nunca se imprimirá';
}
echo $letter;
}
The string BC will be printed since when $ letter is equal to A the iteration does not reach the echo statement $ letter; but it goes back to the beginning of the foreach.
On the contrary, if we do:
$letters = [ 'A', 'B', 'C' ];
foreach ( $letters as $letter) {
if( 'A' == $letter ) {
break;
echo 'Esto nunca se imprimirá';
}
echo $letter;
}
Nothing will be printed because in the first iteration, when $ letter is equal to A, the execution of the foreach structure is finished and none of the echoes is reached.
When break or continue are used in a control structure nested in another, you can specify the number of structures that they affect. The default number is 1 and affects only the current structure. These two structures would be the same:
while ( $foo ) {
$items = [ 1, 2, 3 ];
foreach( $items as $item ) { <--------------------┐
continue; --- vuelve aquí -----┘
}
}
// Esta estructura es igual a la anterior
while ( $foo ) {
$items = [ 1, 2, 3 ];
foreach( $items as $item ) { <--------------------┐
continue 1; --- vuelve aquí -----┘
}
}
while ( $foo ) { <--------------------┐
$items = [ 1, 2, 3 ];
foreach( $items as $item ) {
continue 2; --- vuelve aquí ----┘
}
}