I use ternary operators alot but I can't seem to stack multiple ternary operator inside each other.
I am aware that stacking multiple ternary operator would make the code less readable but in some case I would like to do it.
This is what I've tried so far :
$foo = 1; $bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other"; echo $bar; // display 2 instead of 1
What is the correct syntax ?
Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.
So, why does the ternary operator become so slow under some circumstances? Why does it depend on the value stored in the tested variable? The answer is really simple: the ternary operator always copies the value whereas the if statement does not. Why?
It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
Those parenthesis are what I think is getting you.
Try
$foo = 1; $bar = ($foo == 1) ? "1" : (($foo == 2) ? "2" : "other"); echo $bar;
The problem is that PHP, unlike all other languages, makes the conditional operator left associative. This breaks your code – which would be fine in other languages.
You need to use parentheses:
$bar = $foo == 1 ? "1" : ($foo == 2 ? "2" : "other");
(Notice that I’ve removed the other parentheses from your code; but these were correct, just redundant.)
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