please explain me why am I not getting the whole output with the following line:
echo"$x+$y=".$x+$y."</br>";
I were only getting the print of the addition without the string getting printed. But the output is perfect with this statement:
echo"$x+$y=".($x+$y)."</br>";
Thank you.
This is due to operator precedence for more details you can refer http://php.net/manual/en/language.operators.precedence.php
For visible format you can use
output : $x+$y = 15
Operator precedence 101. The
+
and.
operators have the same precedence and left-to-right associativity, so without braces the operations are evaluated from left to right.Consider this example which I've adapted from your question's code:
Variable names inside double quotes will be expanded (a.k.a. string interpolation) so it is evaluated as follows:
In the question's original code there's one more string concatenation which will concatenate this result with another string and that's it.
¹ From PHP docs:
And of course, you can always use braces to force operations' precedence in order to get the desired result.
You can re-write the expression like this to see the sequence of evaluations:
((("$x+$y=".$x) + $y)."</br>");
Here is what happens in detail:
"$x+$y="
to"10+7="
"10+7=".$x
leading to"10+7=10"
"10+7=10"+$y
evaluates to"10+7"
and eventually"17"
because php attempts to convert the string into a number. During this process it starts at the left side of the string and in your example it finds10
. Next the+
symbol is found, which is not a number and this terminates the attempt to convert the string into a number. However, what has been found to be a number (10
) remains as the numeric interpretation of the string.17
is concatenated with the last string<br>
and this is echoed out.Hope that helps, Loddi