Nested triple php problem: triple output! = If - else

I can use the PHP ternary operator enough. However, I ended up at the checkpoint while trying to find out why the code below does not match the equivalent if-else structure. The test was carried out three times for different numbers. The output for each structure is below the code.

ternary:

$decimal_places = ($max <= 1) ? 2 : ($max > 3) ? 0 : 1; 

Ternary output:

max: -100000 decimal: 0

max: 0.48 decimal: 0

max: 0.15 decimal places: 0

If-else

 if($max <= 1) $decimal_places = 2; elseif($max > 3) $decimal_places = 0; else $decimal_places = 1; 

If-Else Output:

max: -100000 decimal: 2

max: 0.48 decimal: 2

max: 0.15 decimal places: 2

Can someone tell me why these two control structures do not output the same data?

+5
php
Jan 26 '11 at 17:01
source share
4 answers

Your right-handed ternary expression must be enclosed in parentheses, so it will be evaluated on its own as one expression:

 $decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1); // Another way of looking at it $decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1); 

Otherwise, your ternary expression evaluates from left to right, resulting in:

 $decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1; // Another way of looking at it $decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1; 

Which translates to if-else, becomes the following:

 if ($max <= 1) $cond = 2; else $cond = ($max > 3); if ($cond) $decimal_places = 0; else $decimal_places = 1; 

Therefore, $decimal_places ends as 0 for all values โ€‹โ€‹of $max except 2 , in which case it evaluates to 1 .

+18
Jan 26 '11 at 17:03
source share

The code runs as

 $decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1; 

therefore you will never get 2 and 1 only with 1 < $max <=3 . This is due to the fact that the conditional operator is left-associative . Decision. Place the brackets to make sure the order you need is encoded:

 $decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1); 
+2
Jan 26 '11 at 17:03
source share

Just put a bracket, and everything will be fine:

  $decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1); 
+1
Jan 26 '11 at 17:05
source share

As others have indicated, use paranthesis.
However, if you really want to make it readable, what to do about it:

 $decimal_places = ($max <= 1) ? 2 : ( ($max > 3) ? 0 : ( 1 )); 

It still looks very uncomfortable, but this awkwardness has the right shape, making it easier to live with.

 $drink = 'wine'; return ($drink === 'wine') ? 'vinyard' : ( ($drink === 'beer') ? 'brewery' : ( ($drink === 'juice') ? 'apple tree' : ( ($drink === 'coffee') ? 'coffeebeans' : ( 'other' )))); 

You could, of course, omit the last pair of brackets, but that would make it less regular.

+1
Dec 15
source share



All Articles