This question already has an answer here:
This code only prints out '17' instead of "10 + 7 = 17". Why is this? And how can i solve this.
<?
$x = 10;
$y = 7;
echo $x . '+' . $y . '=' . $x+$y;
?>
</div>
This question already has an answer here:
This code only prints out '17' instead of "10 + 7 = 17". Why is this? And how can i solve this.
<?
$x = 10;
$y = 7;
echo $x . '+' . $y . '=' . $x+$y;
?>
</div>
What you should understand is that echo
won't do anything until the result of the whole expression given to it is evaluated. This expression contains both .
and +
operators - the first one concatenates its operands (glues two strings together), the second adds numbers.
Now, you might think that +
operator has a higher precedence than of .
one - in other words, that result of $x + $y
will be calculated before (eventually) glued to the rest of the string. But it's not. So we can say this statement is actually treated as...
echo ($x . '+' . $y . '=' . $x) + $y;
In other words, the result of all the string concatenation is added (converted to number) to $y, and only the result of this operation is printed.
The result of $x . '+' . $y . '=' . $x
is '10+7=10'
, and it doesn't look like something that might be added. But guess what, PHP wants to be nice to you - and it assumes that you actually wanted to extract the first digits of a string when you tried to convert it to a number. So the whole line is treated as number 10
. When added to 7
, it's just 17 - that's why you got 17 echoed.
One possible workaround is getting rid of .
, using ,
operator instead (as its precedence is lower - in fact, it's the lowest among operators):
echo $x, '+', $y, '=', $x + $y;
It could be simplified if one remember about such a handy feature of PHP as string interpolation:
echo "$x + $y = ", $x + $y;