Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The goto statement is an unconditional control flow construct that immediately transfers program execution to a specific, named label within the same script and execution context.

Syntax

The construct consists of two parts: the goto instruction followed by a target identifier, and the target label itself, which is defined by the identifier followed by a colon (:).
goto TargetLabel;

// Intermediate statements are bypassed

TargetLabel:
// Execution resumes here

Mechanics and Naming Rules

  • Label Identifiers: A label name must follow standard PHP naming conventions for variables and functions. It must start with a letter or underscore, followed by any number of letters, numbers, or underscores ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*).
  • Case Sensitivity: Label names in PHP are case-sensitive. goto MyLabel; will not resolve to mylabel:.
  • Instruction Pointer: When the Zend Engine encounters a goto statement, it moves the instruction pointer directly to the opcode associated with the target label, skipping all intermediate code.

Scope and Limitations

PHP imposes strict lexical and contextual boundaries on the goto statement to prevent memory corruption and stack unwinding issues.
  1. Context Boundary: You cannot jump into or out of a function or method. The goto statement and its target label must reside within the same local scope.
  2. File Boundary: You cannot jump between different files. A goto cannot target a label inside an included or required file, nor can it jump out to a parent file.
  3. Control Structure Entry: You cannot jump into any loop (for, while, do-while, foreach) or switch statement. Attempting to do so results in a fatal compilation error.
  4. Control Structure Exit: You can jump out of a loop or switch statement.

Code Examples

Basic Execution Flow:
<?php
echo "Initialization\n";

goto jump_point;

echo "This statement is skipped entirely.\n";

jump_point:
echo "Execution resumed.\n";
?>
Illegal Scope Jump (Fatal Error):
<?php
goto loop_body; // Fatal error: 'goto' into loop or switch statement is disallowed

for ($i = 0; $i < 10; $i++) {
    loop_body:
    echo $i;
}
?>
Legal Control Structure Exit:
<?php
for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
        if ($i === 2 && $j === 5) {
            goto exit_nested_loops;
        }
    }
}

exit_nested_loops:
echo "Exited both loops.";
?>
Master PHP with Deep Grasping Methodology!Learn More