I've recently programmed a lot in javascript and I was trying to use some shorthands in PHP.
Consider this statement:
$value = 1;
return $value == 1 ?
'a' : $value == 2 ? 'b' : 'c';
Could anyone explain me why this returns 'a' in jQuery and 'b' in php?
In PHP, the ternary operator is left-associative (or from the manual, a little less clear).
this is because ternary expressions are evaluated from left to right
In Javascript, the ternary operator is right-associative.
note: the conditional operator is right associative
So, in PHP your code executes like this:
($value == 1 ?
'a' : $value == 2) ? 'b' : 'c';
And in Javascript, it executes like this:
value == 1 ?
'a' : (value == 2 ? 'b' : 'c');
So, to get the same results, you need to tell either one to act like the other:
echo $value == 1 ?
'a' : ($value == 2 ? 'b' : 'c');
This is (one of the?) the reason why nested ternary operators are a bad idea. They're not readable and prone to these kind of mistakes!
You need to wrap the "else" part of the condition in parantheses
$value = 1;
echo $value == 1 ? 'a' : ($value == 2 ? 'b' : 'c');
This would return 'a' in php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With