Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement