3

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?

trusktr
  • 44,284
  • 53
  • 191
  • 263

4 Answers4

8

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

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>';
powtac
  • 40,542
  • 28
  • 115
  • 170
1

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!

SubniC
  • 9,807
  • 4
  • 26
  • 33
1

Alternative using strings.

<?php

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

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

<p>Some other html</p>
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Nice alternative. :) I've used that before to output variables but didn't occurr to use it like that. – trusktr Feb 16 '11 at 09:23