PHP: Is it possible to embed HTML in the middle of a ternary operator somehow?

4.3k views Asked by At

For example, can I do something like the following?

<? $foobar = 1;
$foobar==0 ? ?>
   <span>html goes here.</span>
<? : ?>
   <span>something else.</span>
<? ; ?>

That code won't work. So i'm guessing it's not possible, or is it?

4

There are 4 answers

1
jcubic On BEST ANSWER

Alternative using strings.

<?php

$x = 10;
?>
<p>Some html</p>

<?= $x == 10 ? '<p>true</p>' : '<p>false</p>' ?>

<p>Some other html</p>
0
powtac On

I would recommend to use switch.

Example

<?php
switch($foobar) {
    case 0:
         $html = '<span>html goes here.</span>';
    break;

    default:
    case 1:
         $html = '<span>something else.</span>';
    break;
}

echo $html;

But if you still want to do it with ternary operator, do it like this:

echo $foobar == 0 ? '<span>html goes here.</span>' : '<span>something else.</span>';
0
BoltClock On

You cannot embed HTML like that, because you are terminating the ternary expression prematurely, causing a parse error.

The alternative if-else construct is much more readable. For an extra few characters you get a much more easily-understood block of code:

<?php if ($foobar == 0) : ?>
    <span>html goes here.</span>
<?php else: ?>
    <span>something else.</span>
<?php endif; ?>

You can use the curly-brace syntax too but I don't like seeing stray, unlabeled }s around my code.

0
SubniC On

i think is pointless to use the ternary operator like this, i mean, you are expending 6 lines of code for doing it so is not compact anymore.

I would recomend you to rewrite it as as if/else.

<? $foobar = 0;
if($foobar==0) { ?>
   <span>html goes here.</span>
<? } else { ?>
   <span>something else.</span>
<? } ?>

Best regards.

HTH!