trusktr
trusktr

Reputation: 45464

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

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?

Upvotes: 3

Views: 4444

Answers (4)

SubniC
SubniC

Reputation: 10317

I think it 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>
<? } ?>

Upvotes: 1

jcubic
jcubic

Reputation: 66490

Alternative using strings.

<?php

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

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

<p>Some other html</p>

Upvotes: 1

BoltClock
BoltClock

Reputation: 723668

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.

Upvotes: 9

powtac
powtac

Reputation: 41050

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>';

Upvotes: 1

Related Questions