Wednesday, November 20, 2024
Google search engine
HomeLanguagesWhat is the use of number after “break” or “continue” statements in...

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.




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


Output:

0 1 2 3 

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




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


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.




<?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;
}
?>


Output:

XY

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




<?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;
}
?>


Output:

XYXYXY

RELATED ARTICLES

Most Popular

Recent Comments