Rstar Rstar - 4 months ago 12
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

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

Comments