Ryan Chandler

Goto, or not to goto go

2 min read

The goto statement – feared, ridiculed, yet still lurking around in PHP. Newer PHP developers probably don't even know that it exists and those who do often try to pretend that it doesn't. But is goto really as bad as its reputation suggests?

The goto statement lets you jump from one part of your code to another. You mark a point in the code with a label and then reference it to jump.

goto syke;
echo "You shall not pass.";

syke:
echo "Passed ya!";

That first echo is never actually executed because the goto statement is jumping over it to the syke label. Forgive me for I have sinned.

Most modern languages either completely omit the goto feature, or strongly recommend against using it. It does still have a few niche uses though.

  • Exiting deeply nested loops – instead of numbered break or continue statements, you can add a label and just goto it.
  • Code obfuscation – want code that's impossible to read? Drop in a bunch of goto statements and give someone a heavy headache.
  • Retry mechanisms – instead of doing things with a while loop, use a goto to jump back to a specific point. This is what Laravel's own retry() helper does internally!

Why you should probably avoid it

The main reason developers shun goto is because it makes code hard to follow. Jumping around your code can turn a simple routine into a tangled spaghetti mess. IDEs and language servers do make it easier with "go to X", but you're still better off avoiding it.

Most problems goto was designed to solve are better handled with functions and loops.

So should you use it?

Unless you're writing a short blog post about it, probably not. Knowing that it exists is useful though! Why not drop it into a PR and impress (or scare) your colleagues?