PHP Goto Control Structure

The PHP goto operator was released in PHP 5.3. It permits you to jump from one section of code to another.

Example usage:

for( $x = 0; $x <= 1000; $x++ ) {
    if( $x == 999 ) goto finish;
}
echo "The for loop ended naturally.";

finish:
echo "Exited the loop prematurely and jumped to this location.";

The above block of code outputs ‘Exited the loop prematurely and jumped to this location.’.

While goto may seem like a very useful new operator, use it sparingly (if at all). It’s generally accepted as bad programming practice. Overuse of the goto operator can result in a very confusing program flow. If you have a large application with code jumping all over the place, it is very difficult to read and follow. Wherever possible, try to follow a structured programming approach.

Comments are closed.