0

I have a code like this:

if (true) {
    echo 'one ';
    /* I need to jump out of this block */
    echo 'two ';
}
echo 'three ';

And here is expected result:

one three

How can I do that?

stack
  • 10,280
  • 19
  • 65
  • 117
  • 5
    You may find the following questions elsewhere on Stack Overflow helpful: 1) http://stackoverflow.com/questions/4545769/php-exit-from-if-block; 2) http://stackoverflow.com/questions/7468836/any-way-to-break-if-statement-in-php – Mike Zavarello Jun 26 '16 at 01:45
  • I cannot think of a single use case. Have you a useful example? I'm just curious. – AbcAeffchen Jun 26 '16 at 02:10

3 Answers3

3
do {
  if (true) {
    echo 'one ';
    break;
    echo 'two ';
  }
} while(0);
echo 'three ';

Just use the break function. One can prevent deep nesting full of if-else statements in many cases by breaking

user31415
  • 446
  • 7
  • 16
1

You could just have another if statement. You can only escape out of for, while, and do-while loops using the break statement.

if (true) {
    echo 'one ';
    if (false) {
        echo 'two ';
    }
}
echo 'three ';

goto statements in general are just bad practice.

XKCD

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
0

You can't break out of an if block. There has to be a reason why you'd want to break out there otherwise you'd just remove echo two and be done with it. That being the case, just enclose the rest of the code in another condition so that it only executes when you want it to.