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]:
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.
Your code actually is evaluated as:
(
(
(
$province == 6 ? "city-1" : $province == 7
) ? "city-2" :
$province == 8
) ? "city-3" : $province == 30
) ? "city-4" : "out of borders";
where it should be
$province == 6 ? "city-1" : (
$province == 7 ? "city-2" : (
$province == 8 ? "city-3" : (
$province == 30 ? "city-4" : "out of borders"
)
)
);
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:
$map = array( 6 = >'city-1',
7 => 'city-2',
8 => 'city-3',
30 => 'city-4');
$Myprovince = "out of borders";
if(array_key_exists($province, $map)) {
$Myprovince = $map[$province];
}
Or as @Jonah mentioned in his comment:
$Myprovince = isset($map[$province]) ? $map[$province] : 'out of borders';
if / elseif
orswitch
?switch
as Marc suggested.