This is because the concatenation operator has higher priority than the addition or subtraction operators, but multiplication and division have a higher priority than concatenation.
So what are you really doing:
echo ("$a + $b = " . $a) + $b; echo ("$a - $b = " . $a) - $b;
In the first case, it turns into this:
"1 + 2 = 1" + $b
Which PHP is trying to convert "1 + 2 = 1" to a number (due to the type of juggling ) and gets 1, turning the expression into:
1 + 2
That is why you get 3. The same logic can be applied to the subtraction condition.
Instead, if you place the brackets around the calculations, you get the desired result.
echo "$a + $b = " . ($a + $b); echo "$a - $b = " . ($a - $b);
nickb source share