17

In PHP, is it possible to exit from a PHP code block (i.e. the PHP tags)?

<?php
    if (!A) phpexit();
    print("1");
?>

<?php
    print("2");
?>

So if A was true, then the result is 12, and if A was false, then result is 2.

I know you can do this with if statement or something, but I want to know if there is also some special PHP function that can do this.

5
  • 1
    No, there is no such thing. I even can't imagine where you could use it.
    – ozahorulia
    Jun 16, 2013 at 17:14
  • 13
    Whatever happened to if?
    – deceze
    Jun 16, 2013 at 17:15
  • 2
    What you need is goto but goto = poor design... There's if else for what you need.
    – CodeAngry
    Jun 17, 2013 at 0:21
  • Brake and continue
    – Gucho Ca
    May 16, 2016 at 5:19
  • @GuchoCa break and continue are for loop-structures only. "break ends execution of the current for, foreach, while, do-while or switch structure." stands in the php documentation. Jul 9, 2020 at 15:13

7 Answers 7

33

There is the goto operator but I strongly advise against using this kind of tricks ("spaghetti code"). You better use structured if blocks, there is nothing wrong with them.

Before using goto, consider alternative solutions: for example, you may include different scripts depending on the A condition.

enter image description here

8
  • 5
    I don't downvote this just because of the constructive include part of the answer. The picture is funny, but not constructive. I know it's popular to be agains goto, but goto itself doesn't always mean spaghetti code. To break the program flow, like to jump from the middle of cycle into middle of another function is misusing and spaghetti. But if the jump is clear and doesn't break the context (like in this case), I believe it is OK to use.
    – Jan Turoň
    Jun 16, 2013 at 17:35
  • 2
    @JanTuroň: Yes, I still use goto in some of my C programs, for example to reach a general error handling block from within a nested loop. The problem with goto is that, once you start using it in legitimate ways, you soon start using it to "patch" poorly designed control flows. However, your point is good... and I always try to make my answers constructive.
    – gd1
    Jun 16, 2013 at 18:06
  • 3
    I think that nobody felt that need, simply... Moreover a <?php block is not a structured block, in fact an if can be interrupted by ?> and resumed with <?php. In that case, think about the mess that would come out if such a function did exist.
    – gd1
    Jun 17, 2013 at 14:37
  • 1
    @omega why do we need extra jump's when we can do it already with do-while, if or goto? (and as gd1 points out: it wouldn't be consistent)
    – bwoebi
    Jun 17, 2013 at 14:41
  • 1
    ok I will just avoid goto, and use if blocks then. Thanks everyone.
    – omega
    Jun 17, 2013 at 16:30
20

There could be two solutions:

1) less hacky

include the code you have in the block in separate files. You may use return in them to stop processing included file

//file1.php
if (!A) return;
print("1");

// file2.php
print("2");

<?php include "file1.php";?>
<?php include "file2.php";?>  

2) more hacky (others will probably kill me)

Put the block into do { ... } while(false); block and break from it

<?php do {
    if (!A) break;
    print("1");
} while(false); ?>

<?php do {
    print("2");
} while(false); ?>
5
  • 2
    +1. I'd kill you for the first: wasting a whole file for only one code line :-P But the second I like :-)
    – bwoebi
    Jun 16, 2013 at 17:32
  • 2
    I believe the question was narrowed and the block is some complex consistent code deserving separated file. Maybe. The second one is definitely more suitable for short parts, but may be scary on the first sight.
    – Jan Turoň
    Jun 16, 2013 at 17:40
  • 1
    +1 for the "include" solution and it's good to remark that, if the code blocks are relatively small and simple, than there is no need for inclusion, goto, or "hacky" while loops, and a simple if will do the trick.
    – gd1
    Jun 16, 2013 at 18:13
  • @bwoebi: completely OT, but today you are #6 week rank, you even beat Jon Skeet. Congratulations!
    – Jan Turoň
    Jun 17, 2013 at 0:24
  • @JanTuroň I just saw, thank you… but there are still 5 others who beat me :-P
    – bwoebi
    Jun 17, 2013 at 7:32
12

No there isn't any. But what you could do is putting a label at the end of each block and then use goto (not recommended, but when you don't want a big if... (p.s.: see the answer of @gd1 as a hint here ;-P)).

<?php
    if (!A) goto exit_1;
    print("1");
exit_1: ;
?>

<?php
    print("2");
exit_2: ;
?>
9
  • -1 This is extremely bad coding practice as it leads to spaghetti code en.wikipedia.org/wiki/Spaghetti_code
    – Precastic
    Jun 16, 2013 at 17:18
  • 6
    @Precastic I didn't recommend it, I said it would be the only alternative if the OP strongly feels to have to use it.
    – bwoebi
    Jun 16, 2013 at 17:19
  • 5
    @Precastic: from your link: complex and tangled control structure, especially one using many GOTOs - see the word MANY? Look at Matthias Buelens code (no offense) - this is spaghetti code with tangled structure. The above example is not tangled at all. Goto doesn't always mean spaghetti.
    – Jan Turoň
    Jun 16, 2013 at 17:49
  • 2
    @Precastic a) is a strg + f so hard? And I agree that you should … mostly avoid goto, but there are use cases. Can't instantly tell one in PHP, but in C you can't break multiple nested loops at once. So you simply put there a label at the end of the loops and use goto. If you have X gotos near to each other, or worse overlapping, then you should clearly redesign your code, but nobody should complain about a goto alone where the label is near. (tl;dr: linear jumping is okay (following the programs flow), cross-jumping isn't (jumping back, forward, from one label to the next etc.).)
    – bwoebi
    Jun 16, 2013 at 19:30
  • 1
    @Precastic You didn't get my point. I meant, when we can live with it in another language where it has the exact same syntax, why should we disallow it in PHP? It's (maybe) not best practice, but there's nothing wrong with it.
    – bwoebi
    Jun 16, 2013 at 19:34
8

If this is for anything but an experiment, you are doing it wrong. Stop doing include-oriented programing as start learning OOP.

Well ... you could always wrap the <?php ?> content in anonymous function;

<?php $f = function () use (&$a) {

    if ($a)
    { 
        echo 1;
        return;
    }
    echo 2;

};$f(); ?>

<?php $f = function () {

    echo 2;

};$f(); ?>

This would work in PHP 5.3+. And if you need to share variable, you can inject them in the scope with use() statement in the definition.

But let me repeat:

If you want to do something like this in production code, you are doing it wrong.

6
  • the do { } while (0); is smarter. Doing it with a Closure is correct, but a) slower and using more memory and b) not as beautiful. (but I don't downvote: it's correct)
    – bwoebi
    Jun 16, 2013 at 18:57
  • Hmm.. Now I'm curious. Do the immediately-called functions (like (function() { .. })()) work in PHP (like in Javascript), or is that a syntax error?
    – Izkata
    Jun 16, 2013 at 21:53
  • 1
    @Izkata, i actually tried that initially, but is did not work. Parser was bitching about unexpected parentheses.
    – tereško
    Jun 16, 2013 at 22:13
  • Obviously no downvote, but I may observe that the one who writes in PHP, which is basically a chaos-oriented scripting tool with some late OOP hack, shouldn't fear includes, especially if the alternative is some hackier workaround. :) I agree with your final remark.
    – gd1
    Jun 16, 2013 at 22:44
  • Well ... of course a return from include would be the cleanest solutions.
    – tereško
    Jun 16, 2013 at 22:51
6

If you respect geek pop culture too much and feel you need to fit in (and get popular!), here's a solution without goto:

<?php
call_user_func(function() {
    if (!A) return;
    print("1");
});
?>

<?php
    print("2");
?>
4

No, and it wouldn't make sense. Imagine you could do this and you had this piece of code:

<?php
    if (!A) phpexit();

    if (B) {
?>
        <b>Foo</b>
<?php
    }
?>
    <i>Baz</i>

Where would phpexit() jump to? The then block of the if (B) jumps out and in of a PHP block, but you don't want to jump to <b>Foo</b> from if (!A), right? It wouldn't make sense to jump into a then block without checking the condition.

As gd1 already showed, you could do this with goto but it'd make your code unstructured. You'd make it very hard on yourself (and future maintainers of your code) to understand the flow of your code when your code jumps around all over the place.

In low-level languages (i.e. assembly) you only have jumps to work with, but in higher languages you abstract those away with structures such as if, for and while. These provide structure by intentionally preventing you from jumping to anywhere you want.

0

I've run into several situations where the rest of a PHP code block needs to be skipped over due to an error condition (database connection error, invalid input, etc.). As a student, my professor simply uses die, which stops parsing of the file altogether, leaving the page incomplete, without the footer or even the HTML closing tags </body></html>. Even when there is an error, there is no reason to generate invalid HTML by cutting off the closing tags.

Of course, a purely structured approach would use if statements, and this is preferable to goto in the vast majority of situations. However, I feel that if you're just trying to jump out of a PHP code block, putting large segments of code in an if/else structure is rather inelegant and can actually make the code harder to understand than simply using a goto statement that jumps to the very end of the PHP block, just before the ?>, since it becomes hard to remember that a whole bunch of code is in fact part of a conditional statement 50+ lines below the if or elseif lines.

Everyone says that goto statements are bad, but there are valid uses for goto that make the code easier to understand, such as jumping out of deeply nested control structures and jumping to the end of a PHP code block (given that no built-in language construct exists for doing that).

A code construct like goto is not inherently evil. It comes down to how you use it.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.