Strange behavior of ternary operator and string concatenation?
P粉919464207
P粉919464207 2023-10-21 22:52:32
0
2
522

Hi, I'm just wondering why this code produces (at least for me) incorrect results.

Okay, maybe it's my fault

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

I guess, if paperType is equal to "Bond", the description is "Paper: Bond", if paperType is not equal to "Bond", the description is "Paper: Other".

But when I run this code, the result is that the description is "Bond" or "Other" and leaves me Wondering where the string "Paper:" went? ? ?

P粉919464207
P粉919464207

reply all(2)
P粉204079743

Related to operator precedence. You must do the following:

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

Try adding parentheses so that the string is concatenated to another string in the correct order.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template