Stacking Multiple Ternary Operators in PHP

后端 未结 8 2165
忘了有多久
忘了有多久 2020-11-22 03:49

This is what I wrote :

 $Myprovince = (
($province == 6) ? \"city-1\" :
($province == 7) ? \"city-2\" :
($province == 8) ? \"city-3\" :
($province == 30) ? \         


        
相关标签:
8条回答
  • 2020-11-22 04:18

    Try with some more parenthesis :

    $Myprovince = (
    ($province == 6) ? "city-1" :
    (($province == 7) ? "city-2" :
    (($province == 8) ? "city-3" :
    (($province == 30) ? "city-4" : "out of borders"
    ))));
    

    Your code has a problem with the ternary operator priority.

    But I think you should really drop this operator and try to use a switch instead.

    0 讨论(0)
  • 2020-11-22 04:19

    I got myself into the same problem today. The others already giving acceptable solutions. Mine just an emphasis to one liner ifs. More readable in my opinion.

    if ($province == 6) $Myprovince = 'city-1';
    elseif ($province == 7) $Myprovince = 'city-2';
    elseif ($province == 8) $Myprovince = 'city-3';
    elseif ($province == 30) $Myprovince = 'city-4';
    else $Myprovince = 'out of borders';
    
    0 讨论(0)
提交回复
热议问题