← Back to Chapters

PHP Goto Statement

? PHP Goto Statement

? Quick Overview

The goto statement in PHP allows you to jump to another section of your script. It is often used to jump over certain code or to break out of deeply nested logic. However, its use is discouraged in modern programming because it can reduce readability and maintainability.

? Key Concepts

  • Label acts as a jump target.
  • goto transfers execution to the label.
  • Execution flow becomes non-linear.

⚙️ Syntax / Theory

? View Code Example
// Jump to a defined label
goto label;

// Label definition
label:

? Code Example

? View Code Example
// Demonstrating loop-like behavior using goto
<?php
$counter = 0;

start:
$counter++;
echo "Counter: $counter<br>";

if ($counter < 5) {
goto start;
}
?>

? Live Output / Explanation

The script prints numbers from 1 to 5 by repeatedly jumping back to the start label until the condition becomes false. This mimics a loop without using for or while.

? Interactive Flow Simulator

Watch how the execution "jumps" back to the label until the condition is met.

$counter = 0;
start:
$counter++;
echo "Counter: $counter";
if ($counter < 3) {
  goto start;
}
echo "Done!";
> Ready to simulate...

? Visual Flow (Conceptual)

Start ➜ Increment ➜ Check Condition ➜ goto start ➜ End

? Use Cases

  • Breaking out of deeply nested logic.
  • Skipping sections of code conditionally.
  • Legacy systems where refactoring is limited.

✅ Tips & Best Practices

  • Use goto sparingly.
  • Prefer structured control flow like loops and functions.
  • Always ensure a clear exit condition.

? Try It Yourself

  • Create a file goto_example.php.
  • Print numbers from 1 to 10 using goto.
  • Experiment with multiple labels and jumps.