Ternary operator and string concatenation quirk?

PhpTernary OperatorString Concatenation

Php Problem Overview


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???

Php Solutions


Solution 1 - Php

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

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

Solution 2 - Php

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

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

Solution 3 - Php

I think everyone gave the solution, I would like to contribute the reason for the unexpected result.

First of all here you can check the origin, and how the operators are evaluated (left, right, associative, etc).

http://php.net/manual/fa/language.operators.precedence.php

Now if we analyze your sentence.

$ paperType = 'bond';
$ description = 'Paper:'. ($ paperType == 'bond')? 'Bond': 'Other';
  1. We review the table and find that the parentheses are evaluated first, then the '.' (concatenation) is evaluated and at the end the ternary operator '?', therefore we could associate this as follows:

    // evaluate the parenthesis ... ($ paperType == 'bond') $ description = ('Paper:'. 1)? 'Bond': 'Other'; //result $ description = 'Paper: 1'? 'Bond': 'Other';

  2. We now have the ternary operator, we know that a string is evaluated "true"

// php documentation When converting to boolean, the following values ​​are considered FALSE:

... the empty string, and the string "0"

$ description = true? 'Bond': 'Other';

3) Finally

$ description = 'bond';

I hope I have clarified the question. Greetings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCesarView Question on Stackoverflow
Solution 1 - Phpmeder omuralievView Answer on Stackoverflow
Solution 2 - PhpJoão SilvaView Answer on Stackoverflow
Solution 3 - PhphizmarckView Answer on Stackoverflow