What is the use of number after “break” or “continue” statements in PHP ?

Break and continue are two keywords used to control the iterations in a loop. The major difference between the two keywords is that “break” is used to terminate the loop whereas “continue” skips the current iteration. In order to understand the meaning of numbers written after “break” and “continue” keywords, let us first understand basic “break” and “continue” with the help of examples.

Example 1: This example describes the “break” keyword without number.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$i = 0;
  
for ($i = 0; $i <= 5; $i++) {
    if ($i == 4) {
        break;
    }
    echo $i . " ";
}
  
?>

chevron_right


Output:

0 1 2 3 

Example 2: This example describes the “continue” keyword without number.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$i = 0;
  
for ($i = 0; $i <= 5; $i++) {
    if ($i == 3) {
        continue;
    }
    echo $i . " ";
}
?>

chevron_right


Output:



0 1 2 4 5

Now, we are well versed in the “break” and “continue” keywords, so let us understand these keywords written with a number. A number with the keyword depicts how many nested statements will be affected. For example, for a code with two nested loops, break 2 written in the inner loop to break the execution of both the loops. The same has been depicted with the help of the following codes.

Example 3: This example describes the “break” keyword with number.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$numbers = array(4, 6, 8);
$letters = array("X", "Y", "Z");
  
foreach ($numbers as $num) {
    foreach ($letters as $char){
        if ($char == "Z") {
            break 2; 
        }
        echo $char;
    }
    echo $num;
}
?>

chevron_right


Output:

XY

Example 4: This example describes the “continue” keyword with number.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$numbers = array(6, 8, 10);
$letters = array("X", "Y", "Z");
  
foreach ($numbers as $num) {
    foreach ($letters as $char) {
        if ($char == "Z") {
            continue 2;
        }
        echo $char;
    }
    echo $num;
}
?>

chevron_right


Output:

XYXYXY



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.