PHP is confused when adding and concatenating

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:

echo (("sum:" . $a) + $b);
echo ("sum:" . ($a + $b));

So your first line does the concatenation first and ends up with:

"sum: 1" + 2

(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 result 2.)

Leave a Comment