Question

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.

Was it helpful?

Solution

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:

$x = 3;
$y = 5;
echo "$x+$y=" . $x + $y;

Variable names inside double quotes will be expanded (a.k.a. string interpolation) so it is evaluated as follows:

echo "3+5=" . 3 + 5;
echo ("3+5=" . 3) + 5; //added braces to demonstrate actual operations order
echo "3+5=3" + 5;
echo 3 + 5; //string evaluated in numeric context is coerced to number¹
echo 8;

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:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

And of course, you can always use braces to force operations' precedence in order to get the desired result.

OTHER TIPS

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:

  1. The string is interpolated takes place changing "$x+$y=" to "10+7="
  2. The string concatenation takes place "10+7=".$x leading to "10+7=10"
  3. The addition between a string and a number takes place "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 finds 10. 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.
  4. 17 is concatenated with the last string <br> and this is echoed out.

Hope that helps, Loddi

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

echo '$x+$y='.($x+$y)."</br>";

output : $x+$y = 15

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top