开发者

How to concatenate multiple ternary operator in PHP? [duplicate]

This question already has answers here: Stacking Multiple Ternary Operators in PHP (11 answers) Closed 2 years ago.

I use te开发者_Go百科rnary operators alot but I can't seem to stack multiple ternary operator inside each other.

I am aware that stacking multiple ternary operator would make the code less readable but in some case I would like to do it.

This is what I've tried so far :

$foo = 1;
$bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other";
echo $bar; // display 2 instead of 1

What is the correct syntax ?


Those parenthesis are what I think is getting you.

Try

$foo = 1;
$bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
echo $bar;


The problem is that PHP, unlike all other languages, makes the conditional operator left associative. This breaks your code – which would be fine in other languages.

You need to use parentheses:

$bar = $foo == 1 ? "1" : ($foo == 2 ? "2" : "other");

(Notice that I’ve removed the other parentheses from your code; but these were correct, just redundant.)


You need some parentheses around the right hand operand:

$foo = 1;
$bar = ( $foo == 1 ) ? "1" : (( $foo == 2 ) ? "2" : "other");
echo $bar;

PHP's interpreter is broken, and treats your line:

$bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other";

as

$bar = (( $foo == 1) ? "1" : ( $foo == 2)) ? "2" : "other";

and since that left hand expression evaluates as "true" the first operand of the remaining ternary operator ("2") is returned instead.


Put parenthesis around each inner ternary operator, this way operator priority is assured:

$bar = ( $foo == 1 ) ? "1" : (( $foo == 2 ) ? "2" : "other");


You could write this correctly thus:

$bar = ($foo == 1) ? "1" : (($foo == 2) ? "2" : "other");

(i.e.: Simply embed the 'inner' ternary operator in parenthesis.)

However, I'd be really tempted not to do this, as it's about as readable as a particularly illegible thing that's been badly smudged - there's never any excuse for obfuscating code, and this borders on it.


Just stack up the parenthesis, and you've got it:

$bar = ($foo==1? "1" : ($foo==2? "2" : "other"));

As an aside, if you've got many clauses, you should consider using a switch:

switch ( $bar ) {
  case 1:  echo "1";
  case 2:  echo "2";
  default: echo "other";
}

If the switch gets long, you can wrap it in a function.


$foo = 1;
$bar = ( $foo == 1 ) ? "1" : (( $foo == 2 ) ? "2" : "other");
echo $bar;

Just use extra ( ) and it will work


Add the parenthesis:

$bar = ( $foo == 1 ) ? "1" : (( $foo == 2 ) ? "2" : "other");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜