Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP goto Statement
The goto statement in PHP allows you to transfer program control to a specific labeled location within your code. It's typically used within conditional statements like if, else, or switch constructs to control program flow.
Syntax
statement1;
statement2;
if (expression)
goto label1;
statement3;
label1: statement4;
After statement2, if the expression evaluates to true, program flow jumps to label1. If false, statement3 executes normally. The program then continues with normal execution flow.
Example 1: Conditional Jump
This example demonstrates jumping to a label based on whether a number is even or odd ?
<?php
$x = 10; // Example input
if ($x % 2 == 0)
goto abc;
echo "x is an odd number";
return;
abc:
echo "x is an even number";
?>
x is an even number
Example 2: Creating a Loop
The label can appear before or after the current statement. When the label appears before the goto statement, it creates a loop ?
<?php
$x = 0;
start:
$x++;
echo "x=$x<br>";
if ($x < 5)
goto start;
?>
x=1 x=2 x=3 x=4 x=5
Restrictions
PHP has important restrictions on goto usage. You cannot jump into the middle of loops or switch statements ?
<?php
for ($x = 1; $x <= 5; $x++) {
if ($x == 3)
goto inloop; // This will cause an error
for ($y = 1; $y <= 5; $y++) {
inloop:
echo "x=$x y=$y<br>";
}
}
?>
PHP Fatal error: 'goto' into loop or switch statement is disallowed
Key Points
| Feature | Description |
|---|---|
| Label placement | Can be before or after goto statement |
| Loop creation | Possible when label appears before goto |
| Restrictions | Cannot jump into loops or switch statements |
Conclusion
While the goto statement provides direct control over program flow, it should be used sparingly as it can make code difficult to read and maintain. Modern PHP programming generally favors structured control statements like loops and functions for better code organization.
