Spread the love

Break and continue statements are used to change the flow of program. lets see the difference and usage of both.

Break as the name implies it terminate the current loop and execute the next line of code.

Continue do not terminate the loop rather then it skip the current iteration and execute next itteration.

Example of break:

for ($i = 1; $i <= 5; $i++) {
  
    // Program comes out of loop when
    // i equals to 2.
    if ($i==2)
        break;
    else
        echo($i);
}
echo "\n Program finish";

Output :

1
Program finish

it will check if $i== 2 then it will stop execution of for loop and will process next line of code.

Example of continue:

for ($i = 1; $i <= 5; $i++) {

    // The loop prints all values except 2
 
    if ($i==2)
        continue;
    else
        echo $i.",";
}
echo "\n Program finish";

Output :

1,3,4,5,
Program finish

it will check if $i== 2 then it will skip this iteration and will process next iteration of for loop.

Leave a Reply