【问题标题】:Display html if one of more variables are not empty如果多个变量之一不为空,则显示 html
【发布时间】:2014-12-02 10:11:31
【问题描述】:

如果变量不为空,我想回显一些 html,为此我知道我可以执行以下操作:

if (!empty($test)) {
?>
    <p>Some nice html can go here</p> 
<?php
} 
else 
{ 
echo "It's empty...";
}

如何为多个变量执行此操作?因此,如果其中一个变量不为空,则回显 html?这样可以吗?

if (!empty($test || $image || $anothervar)) {
?>
    <p>Some nice html can go here</p> 
<?php
} 
else 
{ 
echo "It's empty...";
}

【问题讨论】:

    标签: php if-statement echo


    【解决方案1】:

    试试看:

    if (!empty($test) || !empty($image) || !empty($anothervar)) {
      // ...
    }
    

    【讨论】:

      【解决方案2】:

      你应该检查每个变量:

      !empty($test) || !empty($image) || !empty($anothervar)
      

      【讨论】:

        【解决方案3】:

        empty 函数不接受多个参数。

        因此,您需要为每个变量分别使用empty

        最后的代码应该是:

        if (!empty($test)  || !empty($image) || !empty($anothervar)) {
        

        【讨论】:

        • 事实上,OP的代码将唯一的参数传递给empty
        【解决方案4】:

        只需检查所有三个变量。

        另外,我建议您将 php 嵌入到您的 html 中以获得更好的可读性文档,如下所示:

        <?php if (!empty($test) || !empty($image) || !empty($anothervar)): ?>
            <p>Some nice html can go here</p> 
        <?php else: ?>
            It's empty...
        <?php endif; ?>
        

        【讨论】:

          【解决方案5】:

          只是另一种解决方案:

          if(empty($test) and empty($image) and empty($anothervar)) {
             echo "It's completely empty...";
          } else {
          ?>
              <p>Some nice html can go here</p> 
          <?php
          }
          

          或者如果你有很多变量要检查:

          $check = array("test","image","anothervar");
          $empty = true;
          foreach($check as $var) {
             if(! empty($$var)) {
                $empty = false;
             }
          }
          if($empty) {
             echo "It's completely empty...";
          } else {
          ?>
              <p>Some nice html can go here</p> 
          <?php
          }
          

          【讨论】:

            猜你喜欢
            • 2013-08-02
            • 1970-01-01
            • 2012-03-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多