Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP goto statement

Reference for PHP goto: jump to a label in the same file and function, the restrictions on jumping into loops, and cleaner alternatives to use instead.

goto transfers execution to a named label elsewhere in the same file. A label is an identifier followed by a colon. It exists mainly for completeness and for code generators; ordinary application code almost never needs it, and loops, functions and exceptions express the same ideas more clearly.

There are firm rules. You can jump forward or backward, and out of a loop or switch, but never into one. You also cannot jump into or out of a function or method.

PHP
goto done;
echo "skipped";
done:
echo "arrived";

Try it

PHP Forward and backward jumps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Leaving nested loops, and a cleaner alternative

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
goto label;
label:
Name Description
label An identifier defined elsewhere in the same file and function scope, followed by :.

Return value: none.

Errors: a fatal error at compile time if the label does not exist, if you jump into a loop or switch, or if the jump crosses a function boundary.

Usage notes

  • Same scope only. A goto and its label must be in the same function (or the global scope of the same file). You cannot jump out of a function; use return.
  • Cannot jump into a loop or switch. Jumping out of one is allowed.
  • Prefer structured alternatives. break 2 leaves two loops (break and continue), a function with return leaves everything, and exceptions handle error exits.
  • Cleanup patterns. In languages without exceptions, goto cleanup; is a common idiom. In PHP, use try/finally (try, catch, finally).
  • Label names share one namespace per function and cannot be redefined.
  • Readability. Heavy use creates tangled control flow that is hard to test and review. Treat each goto as a code smell.
  • Introduced in PHP 5.3.