【问题标题】:simple php code not working with ternary operator简单的 php 代码不适用于三元运算符
【发布时间】:2013-12-01 16:41:52
【问题描述】:

对于三元运算符,我是一个初学者,以前从未使用过它们。

代码(已简化)

$output2 = '
<div>
    <div>
        <span>test text1</span>
        <div>
            '.(1 == 1) ? "yes" : "no" .'
            <span>test text 2</span>
        </div> 
    </div>
</div>';
echo $output2;

所以问题是,这段代码只输出“是”(只有正确或错误的 if 语句)

我尝试了"" 同样的问题,尝试了不同的条件,尝试了只输出它,没有变量。但问题依然存在。

谢谢。

塞巴斯蒂安

【问题讨论】:

  • 嗯.. 1 实际上等于 1,所以应该返回 yes
  • 是的,但它只返回“是”而不返回“测试文本1”和“测试文本2”
  • 啊,我明白你的意思了。

标签: php ternary-operator


【解决方案1】:

用括号括住你的三元 if,即

$output2 = '
<div>
    <div>
        <span>test text1</span>
        <div>
            '.((1 == 1) ? "yes" : "no") .'
            <span>test text 2</span>
        </div> 
    </div>
</div>';
echo $output2;

【讨论】:

    【解决方案2】:

    在 php 中,三元运算符的行为很奇怪,在你的情况下:

    (1 == 1) ? "yes" : "no" .'<span>test text 2</span>...' 
    

    yes 被认为是第一个结果,"no" . &lt;span&gt;test text 2&lt;/span&gt;... 是第二个结果。为避免此类行为,请始终使用方括号

    ((1 == 1) ? "yes" : "no") .'<span>test text 2</span>...' // works correctly
    

    【讨论】:

      【解决方案3】:

      Alexander's 答案是正确的,但我会更进一步,实际上从字符串中删除三元。

      $ternary = ($something == $somethingElse) ? "yes" : "no";
      
      // Double brackets allows you to echo variables
      //  without breaking the string up.
      $output = "<div>$ternary</div>";
      
      echo $output;
      

      事实证明,这样做更容易维护和重用。


      这里是三元运算符的a few uses。如果使用得当,它们会非常强大。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-16
        • 2012-10-08
        • 2011-12-15
        • 2011-08-21
        • 1970-01-01
        • 2017-11-13
        • 1970-01-01
        • 2014-05-17
        相关资源
        最近更新 更多