PHP Break, Continue, and Goto
In PHP, several control flow statements can be used to alter the flow of execution within loops or conditional statements. These include break, continue, and goto. Here's how each one works:
1. PHP break Statement
The break statement is used to terminate the execution of a loop or a switch statement prematurely. When a break is encountered, the loop or switch block is immediately exited, and the program continues executing the code following the loop or switch.
Syntax:
Example of break in a loop:
Output:
Explanation:
- The loop starts from
$i = 1and continues. - When
$ireaches 5, thebreakstatement is executed, and the loop exits, so it doesn't print numbers greater than 4.
2. PHP continue Statement
The a continue statement is used to skip the current iteration of a loop and move to the next iteration. When the continue statement is executed, the remaining code in the current iteration is skipped, and the loop proceeds with the next iteration.
Syntax:
Example of continue in a loop:
Output:
Explanation:
- The loop starts from
$i = 1and continues. - When
$iis 5, thecontinuestatement is executed, causing the loop to skip that iteration and continue with$i = 6. - As a result, the number 5 is not printed.
3. PHP goto Statement
The a goto statement is used to jump to another part of the code. It's considered controversial because it makes the flow of the program harder to follow, so its usage is generally discouraged. goto allows you to jump to a specific label in the code.
Syntax:
Example of goto:
Output:
Explanation:
- The loop starts with
$i = 0and jumps to thestartlabel. - The value of
$iis incremented and printed. - If
$iis less than 5, it jumps back to thestartlabel and continues the loop. - Once
$ireaches 5, the loop stops, and the program prints "Done!".
Flowchart for break, continue, and goto:
Break:
Continue:
Goto:
When to Use break, continue, and goto:
-
break:- Used when you need to exit a loop or a switch block prematurely, such as when a condition is met that no longer requires further iterations.
-
continue:- Used when you want to skip the current iteration of a loop but continue with the next iteration. It is helpful when certain conditions should exclude specific iterations.
-
goto:- Use sparingly as it can lead to code that is difficult to follow. It is usually better to use proper control flow like loops and functions.
gotois typically used for error handling in some cases, but its use is often discouraged in modern programming practices.
- Use sparingly as it can lead to code that is difficult to follow. It is usually better to use proper control flow like loops and functions.
Important Notes:
breakandcontinuework well within loops andswitchstatements.gotoshould generally be avoided in favor of cleaner control structures.

