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?
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?
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>';
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.
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!
Alternative using strings.