51

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?

5
  • 9
    Is there a reason you don't want to just use if / elseif or switch ?
    – Jim
    Commented Mar 8, 2011 at 16:58
  • 2
    You'd need many more brackets for this to work. User a switch as Marc suggested. Commented Mar 8, 2011 at 16:59
  • @Mac: you're driving me crazy with curiosity :D ! Why do you need to use ternary operators?
    – Jonah
    Commented Mar 8, 2011 at 17:03
  • 6
    Using ternary operators with complex nested conditions is not recommended for very good reasons... because they're fraught with problems, and it's extremely difficult to identify bugs. You've just discovered this! If you really knew how to use them, you wouldn't be asking for help! So why do you still want to use ternary operators in this case?
    – Mark Baker
    Commented Mar 8, 2011 at 17:04
  • im using ternary operators because of my own curiosity nothing else , i know its not good for complex conditions statement but in learning and testing php details i need to correct it :D
    – Mac Taylor
    Commented Mar 8, 2011 at 17:06

9 Answers 9

113

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

1
  • 3
    I think it is not a good response to reject the use of chained ternary as a programming pattern. It makes for concise clear code in the numerous languages that implement it "properly" and because it generates an expression, sometimes it is the only way to quickfix something. I used quotes because while the PHP designers did make the asinine choice to make its ternary operator left-associative, the fact is well-documented.
    – Steven Lu
    Commented Jun 10, 2015 at 6:07
39

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';
8
  • 2
    Make it even shorter with this: $Myprovince = isset($map[$province]) ? $map[$province] : 'out of borders'; ;-)
    – Jonah
    Commented Mar 8, 2011 at 17:02
  • @Jonah: True :D I guess I wanted to go away from the ternary operator as far as possible ;) Commented Mar 8, 2011 at 17:06
  • To your edit, I believe that the other lines are the c statements for the previous lines. Notice, no semi-colons. It's pretty much just: ($province == 6) ? "city-1" : ($province == 7) ? "city-2" : ($province == 8) ? "city-3" : ($province == 30) ? "city-4" : "out of borders";
    – Phoenix
    Commented Mar 8, 2011 at 17:10
  • @Phoenix: Yeah I noticed it and fixed it. I got very confused by all this ? and : ;) Commented Mar 8, 2011 at 17:15
  • 4
    Note that PHP 8 has disabled nested ternaries without explicit parentheses.
    – Barmar
    Commented Dec 23, 2021 at 21:37
19

Don't abuse the ternary operator for that sort of thing. It makes debugging near impossible to follow. Why not do something like

switch($province) {
    case 6: $Myprovince = "city-1"; break;
    case 7: ...
}

or simply some chained if/then/else

if ($province == 6) {
     $Myprovince = "city-1";
} elseif ($province = ...) {
   ...
}
5
  • didn't i mentioned that i insist in using tenary operators because some reasons ?
    – Mac Taylor
    Commented Mar 8, 2011 at 16:58
  • 6
    @Mac Taylor: No you didn't. What is the reason? Obscurity? Commented Mar 8, 2011 at 16:59
  • @Felix: perhaps debugging masochism?
    – Marc B
    Commented Mar 8, 2011 at 17:01
  • 3
    The big benefit of the ternary over these is that it allows having a single variable assignment. Commented Nov 5, 2015 at 22:13
  • AND DO NOT FOREGET, switch - case is always faster that if - else branched ! Commented Sep 15, 2022 at 17:12
15

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:

$provinces = array (
    6 => 'city-1',
    7 => 'city-2',
    8 => 'city-3',
    30 => 'city-4'
);

// then you can call:

$Myprovince = isset($provinces[$province]) ? $provinces[$province] : 'out of borders';

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.

0
6

The best and most readable (IMO) solution for this was introduced with the match expression in PHP 8:

$Myprovince = match ($province) {
    6       => "city-1",
    7       => "city-2",
    8       => "city-3",
    30      => "city-4",
    default => "out of borders",
};

It's essentially just a less-verbose switch statement (or a more complex ternary expression) that's used for simple assignment based on the value of an expression. Multiple conditions can be added as well:

$Myprovince = match ($province) {
    4, 5, 6  => "city-1",
    7, 9, 10 => "city-2",
    8        => "city-3",
    30       => "city-4",
    default  => "out of borders",
};
1
  • I was just wondering if there existed some PHP equivalent of Java's switch expression. Well, here it is.
    – MC Emperor
    Commented Feb 2, 2023 at 0:03
3

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.

3

I think the more readable way to write nested ternary operators in PHP is like this:

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

All you need to do is count the number of opening parenthesis (() and add the same number of closing parenthesis ()) at the end of the last line.

Another option is to use one-line if/elseif/else, as already suggested - however, I would format them visually like this for even more readability:

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";
2

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';
1
  • Switches are ugly, yes, but better would be a lookup array with a isset() check -- easy and clean. Commented Feb 9, 2021 at 6:31
1

Use switch instead. Ternary operators really shouldn't be used for more than single conditions, as they quickly become very difficult to understand.

switch ($province) {
    case 6:
        $Myprovince = 'city-1';
        break;
    case 7:
        $Myprovince = 'city-2';
        break;
    case 8:
        $Myprovince = 'city-3';
        break;
    case 30:
        $Myprovince = 'city-4';
        break;
    default:
        $Myprovince = 'out of borders';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.