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.
// Jump to a defined label
goto label;
// Label definition
label:
// Demonstrating loop-like behavior using goto
<?php
$counter = 0;
start:
$counter++;
echo "Counter: $counter<br>";
if ($counter < 5) {
goto start;
}
?>
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.
Watch how the execution "jumps" back to the label until the condition is met.
Start ➜ Increment ➜ Check Condition ➜ goto start ➜ End
goto sparingly.goto_example.php.goto.