nested php ternary trouble: ternary output != if – else [duplicate]

Your right-hand-side ternary expression needs to be wrapped in parentheses so it’ll be evaluated by itself as a single 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 is evaluated 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, translated to if-else, becomes this:

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

if ($cond)
    $decimal_places = 0;
else
    $decimal_places = 1;

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

Leave a Comment