可以使用速记If / Else语句是否包括或更多Else If?

I've been looking around for a decisive answer to whether or not short hand if / else statements can include else ifs. I use them fairly regularly when I'm just assigning a value to a variable and the usually work. However every once in a while they return unexpected results.

I've tried looking for a definitive answer such as these statements should not include else ifs but I cant find it in the documentation.

To better explain lets say I have the following if statement in PHP:

$type = 'one';
$choice = ($type == 'one') ? 'One Fish' : ($type == 'two') ? 'Two Fish' : 'Three Fish';

Why would this return 'Two Fish' as a result? I've experienced this in multiple languages including PHP and JS. Am I just trying to do something I shouldn't?

You need to wrap the "else" part of your first test in parentheses, so it gets interpreted correctly.

$choice = ($type == 'one')
           ? 'One Fish'
           : (($type == 'two') ? 'Two Fish' : 'Three Fish');

Here's some advice for you on using the ternary operator.

My advice to you would be to keep shorthand simple if/else statements and code "longhand" for anything more complex.

The reason for this is longevity, you will find it much easier to read your code months down the line etc. If you're workin within a team, it will make your code much more team friendly!