Web Development

GOTO is coming to PHP!

GOTO, the infamous much-loathed feature of languages in decades gone by, is (sort of) coming to PHP. Read on to see why it’s actually a good thing.
Luckily, it’s not that bad. In fact, it’s quite handy.

Take a look at the following scenario:

while($var)
{
foreach ($var as $val)
{
if ($val) break 2;
}
}

Now, consider all this is inside another while loop. If someone else comes in and refactors, taking out the foreach loop, your ‘break 2;’ suddenly not only breaks out of the while($var) but also the loop outside of it. Big trouble.

Of course, GOTO is associated with Bad Things. A GOTO of sorts is coming to PHP 6, and is actually a good thing. It’s not so much a GOTO as a named break – it allows you to use your break statements to go to a particular point in code execution, as opposed to all this messy nested looping and loop numbering. Here’s a sample:

for ($i = 0; $i < 9; $i++)
{
if (true) {
break blah;
}
echo "not shown";
blah:
echo "iteration $i\n";
}
?>

I believe it was discussed at a meeting some time back; see here for the meeting notes. In any case, it’s a useful addition, provided it isn’t misused; hopefully we won’t end up with the spaghetti code messes of years gone by.

About the author

Written by .

If you found this post useful you may also want to check these out:

  1. Validating Form Input – II
  2. Use Stack Variables Whenever Possible
  3. Control Structures and While Loops
  4. Using Arrays in JavaScripts
  5. Creating a PHP Looping Statement
  6. Using Control Structures and Foreach Loops in PHP
  • Anonymous

    THAT IS NOT A GOTO.

    They horribly neutered a perfectly good and long-needed goto command in the earlier betas into this piece of crap. As you say, it’s a labeled break. Sure, labeled breaks are good, but you can’t POSSIBLY call this a goto. PHP needs a REAL goto, ffs.

    I’d sooner write my own webserver than use this bullshit crap.

  • Frank Rizzo

    You should stop coding if you really think that PHP needs a goto.