views:

434

answers:

2

Hi I just want to know why this code yields (at least for me) an incorrect result.

Well, probably i'm in fault here

$description = 'Paper: ' . ($paperType == 'bond') ? 'Bond' : 'Other';

I was guessing that if paperType equals 'Bond' then description is 'Paper: Bond' and if paperType is not equals to 'Bond' then description is 'Paper: Other'.

But when I run this code the results are description is either 'Bond' or 'Other' and left me wondering where the string 'Paper: ' went???

+13  A: 
$description = 'Paper: ' . ($paperType == 'bond' ? 'Bond' : 'Other');

Try adding parentheses so the string is concatenated to a string in the right order.

meder
Yes, it works, so is a operator precedence problem in my code, shame on me ;~)
Cesar
But i don't really fully understands whats happening...
Cesar
'Paper: ' is being first applied to a boolean ( the result of $paperType == 'bond' ), in other words code is not happening in the right order.
meder
And to resolve that by specifying parentheses you're basically saying, please return either 'Bond' or 'Other' and then add it to 'Paper: ' INSTEAD OF trying to add 'Paper: ' to true or false.
meder
I get it now, when i concatenate 'Paper: ' to a boolean the result is either 'Paper: ' is the comparison is false or 'Paper: 1' if true, but either way the resulting string evaluate to TRUE, so in my particular case, description will ALWAYS be set to 'Bond', no matter what.Very Thanks.Muchas Gracias!
Cesar
Yes, that is correct, and it happens because the "." operator has precedence over the "?:" operator.
JG
+2  A: 

It is related with operator precedence. You have to do the following:

$description = 'Paper: ' . (($paperType == 'bond') ? 'Bond' : 'Other');
JG