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?
Don't abuse the ternary operator for that sort of thing. It makes debugging near impossible to follow. Why not do something like
or simply some chained if/then/else
Some people have suggested using a switch statement or an if/else statement. But I would use an array instead, to make it easier to maintain and easier to read:
Why?
The code will probably eventually be easier to manage. Maybe you'll want to add those province-to-city mappings from database one day.. etc.. That will be hard to maintain with a bunch of switch/case statements.
I understand this is a question about PHP, but since this is just an educational exercise anyways I thought you might be interested in learning that Ruby and Javascript actually behave the way you expect.
Ruby:
Javascript:
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:
Updated Link
The ternary operator is evaluated from left to right. So if you don't group the expressions properly, you will get an unexpected result.
PHP's advice is [docs]:
Your code actually is evaluated as:
where it should be
This code might look fine but someone will read it and they will need more time than they should to understand what this code is doing.
You would be better off with something like this:
Or as @Jonah mentioned in his comment:
Use switch instead. Ternary operators really shouldn't be used for more than single conditions, as they quickly become very difficult to understand.