Nested PHP Ternary Trouble: Ternary Output != If - Else

nested php ternary trouble: ternary output != if - else

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.

Stacking Multiple Ternary Operators in PHP

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

How to replace if statement with a ternary operator ( ? : )?

The

(condition) ? /* value to return if condition is true */ 
: /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
/* condition is true, do something like echo */
}
else {
/* condition is false, do something else */
}

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

corresponding nested ternary operator in php?

Ternary operators are tricky thing in PHP, as they are left-associative (unlike all other languages, where it's right-associative). You will need to use parenthesis to tell PHP what you want exactly in this case:

echo ($projectURL ? $projectURL : ($project['project_url'] ? $project['project_url'] : $project['project_id']));

Comparison Operator IF in PHP

Try it with grouping:

$bonus = $db->f('item_bonus') > 0 ? $db->f('item_bonus').' (i)' : ($db->f('manufacturer_bonus') > 0 ? $db->f('manufacturer_bonus').' (m)' : ($db->f('category_bonus') > 0 ? $db->f('category_bonus'). ' (c)' : '0'));

PHP calculation - why is 1+1=3?

PHP's evaluation of the ternary (or conditional) operator is a bit different from that of other languages.

1+1==2 ? 2 : 1+2==2 ? 3 : 2

Most languages (e.g. JavaScript) would evaluate this as:

(1+1==2) ? (2) : ( (1+2==2) ? (3) : (2) ) 
=> 2

PHP, however, evaluates this as:

( (1+1==2) ? (2) : (1+2==2) ) ? (3) : (2)
=> 3

So because (1+1==2) evaluates to true, the result of the first ternary expression evaluates to 2, and that result is then passed to the second ternary expression, which evaluates to 3.

This behavior is alluded to in the documentation:

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…

The Wikipedia article on the ?: operator also mentions this:

Due to an unfortunate error in the language grammar, the implementation of ?: in PHP uses the incorrect associativity when compared to other languages…

The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches: c1 ? o1 : c2 ? o2 : o3 is really ((c1 ? o1 : c2) ? o2 : o3). This is acknowledged and will probably not change.

  • See also: Bug #61915

PHP nested ternary if condition

use below code

<?php
$var = 4;
echo $current = (($var > 2) ? "gr than 2" : (($var > 6) ? "gr than 6" : "not gr than 2 or 6") );
?>

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

PHP ternary operators: if/else if/else with NULL, 0 and 1

It doesn't seem to be a correct logic.

I suppose, I should be as follows:

if (isset($mobileNumberHF['IS_VALID'])) {
echo ($mobileNumberHF['IS_VALID'] != 0)? '<strong class="text-success">Validado</strong>' : '<strong class="text-danger">Inválido</strong>';
} else {
echo '<strong class="text-warning">Sin validar</strong>';
}

As for your ternary operator: you have misplaced parenthesis in the last operand. Also 'Hasn't word has unescaped single quote.

$isValidMobileNum = 1;
$mobileNumStatusLabel = ($isValidMobileNum == 1) ? 'Valid' : (!isset($isValidMobileNum) ? 'Hasn\'t been validated' : 'Invalid');
echo $mobileNumStatusLabel; // "Valid"


Related Topics



Leave a reply



Submit