简单的php代码不使用三元运算符


simple php code not working with ternary operator

当谈到三元运算符时,我是一个非常初学者,以前从未使用过它们。

代码(已简化)

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

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

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

谢谢。

Sebastjan

用括号包围三元if,即

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

在php中,三元运算符的行为很奇怪,在您的例子中:

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

yes被认为是第一个结果,而"no" . <span>test text 2</span>...被认为是第二个结果。为了避免这种行为,总是使用括号

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

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

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

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


以下是三元运算符的一些用法。如果你使用得当,它们会非常强大。