开发者

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>so开发者_如何学Pythonmething else.</span>
<? ; ?>

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


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.


Alternative using strings.

<?php

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

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

<p>Some other html</p>


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜