Rstar Rstar - 1 year ago 77
PHP Question

what is the difference between these two lines

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

Answer Source

Consider this code:

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

Left is first


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

Right is first

The exaplanation can be found at

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download