How to enclose HTML in a ternary operator condition as you would with a normal if statement

98 Views Asked by At

When I'm using the IF Statement, I normally do something like this:

    <?php 
    if ($var ===0){ ?>
    <section>We broke out of PHP</section>
    <?php ////// we are back in PHP 
    } else {

        }       
 ?>

How can I archive the same thing with a ternary operator, something like:

  <?php 
    $var ===0?: $_breakHere?>
    <section>We broke out of PHP</section>
    <?php ////// we are back in PHP 
    $_ContinueHere
    } else {

        }       
 ?>

I'd put all the html block into a PHP variable, but I want to break our of PHP and back into it, for syntax reading purposes.

1

There are 1 best solutions below

0
On

Syntactically, the expression with the ternary operator, is a single instruction, and you cannot break a single instruction across PHP tags, regardless of nesting PHP and HTML code blocks.

For example, the followings generate syntax errors:

<?php echo 1==2 ? "eq" : ?><?php "ne"; ?> // syntax error, unexpected '?>'
<?php $seven = ?><?php 7; ?>              // syntax error, unexpected '?>'