Home  >  Q&A  >  body text

Strange behavior of ternary operator and string concatenation?

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粉919464207P粉919464207337 days ago439

reply all(2)I'll reply

  • P粉204079743

    P粉2040797432023-10-22 22:16:47

    Related to operator precedence. You must do the following:

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

    reply
    0
  • P粉448130258

    P粉4481302582023-10-22 09:37:19

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

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

    reply
    0
  • Cancelreply