Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacking Multiple Ternary Operators in PHP

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?

like image 414
Mac Taylor Avatar asked Mar 08 '11 16:03

Mac Taylor


People also ask

Can you stack ternary operators?

Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.

Is there ternary operator in PHP?

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.

How to do ternary operator in PHP?

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.

What is the use of ternary Operators in c?

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");


1 Answers

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

like image 120
codaddict Avatar answered Sep 21 '22 18:09

codaddict