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.
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.
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); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With