如何将IF语句放在字符串中?

时间:2017-02-06 14:12:53

标签: php

如何将IF语句放在这样的字符串中?

<?php echo
"<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='" . base_url() . "gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />

      //I want to put IF here
      <button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>  
      //END here

    </form>
 </div>";
?>

3 个答案:

答案 0 :(得分:2)

试试这个。

<?php echo
"<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='" . base_url() . "gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />
";

if(expression)      //put IF here
{
    //put multiple statements if any
    echo "<button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>  ";
}

echo "</form></div>";
?>

在此之后请理解&#39;如何使用PHP嵌入PHP&#39;

希望这会对你有所帮助。

答案 1 :(得分:0)

您可以预先测试您的状况并将结果放在变量中。如果条件失败,只需将其等于空字符串即可。这里使用三元运算符进行分配。

<?php

$base_url  = '/';
$image     = "foo";
$condition = true;

$submit = $condition
    ? "<button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>" 
    : '';

echo
"<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='${base_url}gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />
      $submit
    </form>
 </div>";

或者,您可以连接字符串并使用三元运算符。但这可能会变得混乱。

<?php
echo
 "<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='${base_url}gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />
      " . ($condition ? "<button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>" : ''). "
    </form>
 </div>";

您可以使用逗号删除括号:

<?php
echo
 "<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='${base_url}gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />",
      $condition ? "<button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>" : '',
      "</form>
 </div>";

答案 2 :(得分:-1)

我解决了这个问题:

<?php
<div class='portfolio-info'>
   <form id='imgtitle' class='kart' action='" . base_url() . "gallery/delete' method='post'>
      <input type = 'hidden' name='delete_file' value='$image' />";?>
         <?php if($_SESSION['admin']==1):?>  
            <button type = 'submit' class='btn btn-danger'><i class='delete fa fa-trash fa-3x'></i></button>
          <?php endif; ?>
<?="</form>
</div>
?>