If you look at the page listing PHP operator precedence, you'll see that the concatenation operator .
and the addition operator +
have equal precedence, with left associativity. This means that the operations are done left to right, exactly as the code shows. Let's look at that:
$output = "sum: " . $a;
echo $output, "\n";
$output = $output + $b;
echo $output, "\n";
This gives the following output:
sum: 1
2
The concatenation works, but you then try to add the string sum: 1
to the number 2
. Strings that don't start with a number evaluate to 0
, so this is equivalent to 0 + 2
, which results in 2
.
The solution, as you suggest in your question, is to enclose the addition operations in brackets, so they are executed together, and then the result of those operations is concatenated.
echo "sum: " . ($a + $b);