Welcome to my series on every PHP keyword and its usage. Today’s item: goto.

The goto statement allows you to jump around in the current context, disregarding normal code flow. Using goto should be avoided in most situations, as it makes it harder to reason about your code.

In PHP, goto is restricted to the current file, and the current context. This means that you can not jump to another file, nor can you jump into or out of a function.

In most situations where you might be tempted to use goto, you should consider either using a loop, or refactoring into a function. Using goto can have negative results:

Comic depicting a raptor attacking a programmer who opts to use goto

Comic courtesy of xkcd

Usage

If you must use goto:

1
2
3
4
5
6
7
8
9
<?php
// A label can be any combination of digits, letters and underscores, as long
// as it does not start with a digit
first:
goto second;

// Look we've made an infinite loop!
second:
goto first;