I have the following code:
<?php
$a = 1;
$b = 2;
echo "sum: " . $a + $b;
echo "sum: " . ($a + $b);
?>
When I execute my code I get:
2
sum: 3
Why does it fail to print the string "sum:"
in the first echo? It seems to be fine when the addition is enclosed in parentheses.
Is this weird behaviour anywhere documented?
Both operators the addition
+
operator and the concatenation.
operator have the same operator precedence, but since they are left associative they get evaluated like the following:So your first line does the concatenation first and ends up with:
(Now since this is a numeric context your string gets converted to an integer and thus you end up with
0 + 2
, which then gives you the result2
.)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:This gives the following output:
The concatenation works, but you then try to add the string
sum: 1
to the number2
. Strings that don't start with a number evaluate to0
, so this is equivalent to0 + 2
, which results in2
.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.
Since you use the language construct
echo
you can use a comma to separate the addition from the concatenation:Works as expected.