Question

this is probably so simple but still i can't get it to work i'm using this statement:

echo "$num1"."+"."$num2"."=".$num1+$num2."<BR>";

i was expecting something like 3+3=6 but instead i get just 6

any ideas why?

Was it helpful?

Solution

Put parens around the addition. This is an order of operations conflict.

echo "$num1"."+"."$num2"."=".($num1+$num2)."<BR>";

The reason is PHP had interpreted the expression as if it were:

$a = "$num1"."+"."$num2"."=".$num1;
$b = $num2."<BR>";
echo $a + $b;

When adding strings, PHP tries to cooerce a number out of it. The first number in the $a string is $num1 or "3". It does the same for $b, getting $num2 or "3". Thus, $a+$b is 6.

OTHER TIPS

echo "$num1"."+"."$num2"."=".($num1).+.($num2)."<BR>";

it may work!!!

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