0

This code echo "2" instead of "2some text"!

$x = 2;
echo $x??0 . "some text";

If we put the $x??0 in parentheses, the result is correct:

$x = 2;
echo ($x??0) . "some text";

now result is: 2some text

Is something wrong in the above code or is a php bug?

1
  • No need to concatenate output with echo using a .. You can use a , (comma) instead. Commented Nov 6, 2019 at 16:56

1 Answer 1

4

This is the correct behavior. The string concatenation . operator has higher precedence than the null coalesce operator ??, so (as you've noted) you need to use parens to force the desired behavior. Without parens, the code is interpreted as if you had done this:

echo $x ?? (0 . "some text");

See here for details.

Sign up to request clarification or add additional context in comments.

1 Comment

may be worth noting that without the brackets around the $x??0 - it's comparing 2 vs 0.some Text - which of course renders 2 because $x is not null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.