为什么PHP会产生意外的输出?

Ahm*_*mad 3 php c# conditional

$i = 2;
$result = ($i == 2) ? "Two" : ($i == 1) ? "One" : "Other";

echo $result; // outputs: One
Run Code Online (Sandbox Code Playgroud)

虽然C#输出中的代码相同:两个

int i=2;
String result = (i == 2) ? "Two" : (i == 1) ? "One" : "Other" ;
Console.Write( result ); // outputs: Two
Run Code Online (Sandbox Code Playgroud)

lig*_*ght 5

三元运算符被评估为LEFT-TO-RIGHT.

($i == 2) ? "Two" : ($i == 1) ? "One" : "Other"
"Two" ? "One" : "Other"  // first part evaluated to "Two"
"One"                    // non-empty strings evaluate to true
Run Code Online (Sandbox Code Playgroud)

所以你应该进入One你的输出,而不是Other.这有点棘手.

手册中的明智之词:

建议您避免"堆叠"三元表达式.PHP在单个语句中使用多个三元运算符时的行为是不明显的.