Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from PHP code block?

Tags:

html

php

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.

like image 737
omega Avatar asked Jun 16 '13 17:06

omega


2 Answers

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

like image 102
gd1 Avatar answered Sep 28 '22 08:09

gd1


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); ?>
like image 35
Jan Turoň Avatar answered Sep 28 '22 07:09

Jan Turoň