Stacking Multiple Ternary Operators in PHP

后端 未结 8 2329
忘了有多久
忘了有多久 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:16

    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';
    

提交回复
热议问题