-2

getting 2 different outputs while using the same currency 'egp'

$currency = ($q->currency == 'egp')? '£' : (($q->currency == 'usd') ? '$' : '€');

this line outputs $

$currency = ($q->currency == 'egp')? '£' : ($q->currency == 'usd') ? '$' : '€';

this one outputs £

and I can't find why?

note: the only difference is the () around the second ternary operator statement

Romany Saad
  • 115
  • 1
  • 9
  • 4
    The removal of the extra () causes the precedence of the operators to change. If you need to do this kind of thing, I usually recommend switching to `if elseif else` standard syntax for ease of use, readability and understanding. – Jonnix Jul 06 '16 at 13:42
  • 1
    Ternary operations are awesome, for short and simple checks. Nested ternary operations should be illegal. – M. Eriksson Jul 06 '16 at 13:47

1 Answers1

1

Consider this code:

echo (true?"Left is first":(true?"Right is first":""));

Left is first

Versus

echo (true?"Left is first":true?"Right is first":"");

Right is first

The exaplanation can be found at http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary.

In short, in the second case PHP will evaluate true?"Left is first":true as the condition for the ternary expression. This will evaluate to Left is first which evaluates to true and therefore Right is first will be echoed

apokryfos
  • 38,771
  • 9
  • 70
  • 114