This is what I wrote :
$Myprovince = ( ($province == 6) ? "city-1" : ($province == 7) ? "city-2" : ($province == 8) ? "city-3" : ($province == 30) ? "city-4" : "out of borders" );
But for every field I got the value city-4
. I want to use ternary operators instead of switch/if
because I want to experiment and see how it would be done.
What's the problem with this code?
Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.
The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2); Condition: It is the expression to be evaluated and returns a boolean value.
We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
Others have already suggested the right way of doing it but if you really want to use ternary operator you need to use parenthesis as:
$province = 7; $Myprovince = ( ($province == 6) ? "city-1" : (($province == 7) ? "city-2" : (($province == 8) ? "city-3" : (($province == 30) ? "city-4" : "out of borders"))) );
Updated Link
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