Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PHP give unexpected output?

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

echo $result; // outputs: One

While the same code in C# outputs: Two

int i=2;
String result = (i == 2) ? "Two" : (i == 1) ? "One" : "Other" ;
Console.Write( result ); // outputs: Two
like image 532
Ahmad Avatar asked Feb 18 '26 23:02

Ahmad


1 Answers

Ternary operators are evaluated 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

So you should get One in your output, not Other. It's a little tricky.

Wise words from the manual:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

like image 177
light Avatar answered Feb 20 '26 11:02

light



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!