如何在字符串中插入php if语句

时间:2019-02-16 16:58:33

标签: php html

我正在为我创建的一个小网站编写代码,我试图将其放置在字符串中它将运行'if'语句的位置,而不仅仅是显示在屏幕上。

$posts .= "<div class='posts'><p>$output</p> if($showName == 1){echo: '<h4>Posted by: $name</h4>';} </div>";

echo: "$posts";

如果$ showName等于“ 1”,我希望它显示“ Posted by:Dylan”。如果$ showName等于'0',则'if'语句内将不显示任何内容。当前正在显示

if(1 == 1){echo: '
Posted by: Dylan
';}

很抱歉,如果这样做不好。这是我在这里的第一篇文章。 如有任何疑问,我会尽快答复

2 个答案:

答案 0 :(得分:1)

您可以使用三元运算符并按如下所示更改代码

<div class="flex-container">
  <table class="beirat_l">
    <tbody>
      <tr>
        <td>
          <img alt="Dr. Heiko Breit" class="img-responsive" height="241" src="http://kloss.biz/media/pics/Dr.-Heiko-Breit.jpg" style="" width="254" /></td>
      </tr>
      <tr>
        <td>Dr. Heiko Breit</td>
      </tr>
    </tbody>
  </table>

  <table class="beirat_r">
    <tbody>
      <tr>
        <td>
          <img alt="Dr. Heiko Breit" class="img-responsive" height="241" src="http://kloss.biz/media/pics/Dr.-Heiko-Breit.jpg" style="" width="254" /></td>
      </tr>
      <tr>
        <td>Dr. Heiko Breit</td>
      </tr>
    </tbody>
  </table>
</div>

答案 1 :(得分:0)

我将响应收集到一个名为response的变量中,然后将其附加到字符串中。

if($showName == 1){
$response =  '<h4>Posted by: '.$name.'</h4>';
}else{
$response = '';
}
$posts = "<div class='posts'><p>".$output."</p>".$response."</div>";
echo $posts;