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

Seb*_*jan 0 php ternary-operator

对于三元运算符来说,我是一个初学者,以前从未与他们合作过.

代码(简化)

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

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

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

谢谢.

Sebastjan

u_m*_*der 7

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

(1 == 1) ? "yes" : "no" .'<span>test text 2</span>...' 
Run Code Online (Sandbox Code Playgroud)

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

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


Ale*_*kov 5

if用括号围绕你的三元组,即

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