Simple arithmetic in PHP

Go To StackoverFlow.com

5

Here is a simple php program which gives a strange output. Can anyone explain why it is coming like this and how to get the expected output?

<?php
$a=2;$b=3;

echo "<br> ADD:".$a+$b;
echo "<br> SUB:".$a-$b;
echo "<br> MUL:".$a*$b;
echo "<br> DIV:".$a/$b;
?>

Output:

3-3
MUL:6
DIV:0.66666666666667

Expected Output:

ADD:5
SUB:-1
MUL:6
DIV:0.66666666666667
2012-04-04 16:35
by Stranger


12

It is because the string concatenation operator . has the same precedence as the add/sub operators, and all of them are left-associative. This means that evaluation proceeds left-to-right, so "<br> ADD:".$a is evaluated first and the result is added to 3. This particular string converts to zero and 0 + 3 = 3. Similar for the subtraction.

Solution: put the arithmetic in parentheses.

echo "<br> ADD:".($a+$b);
echo "<br> SUB:".($a-$b);

On the other hand, mul/div have higher precedence than concatenation so they produce the expected result.

2012-04-04 16:37
by Jon
Great answer Jon! Thank you - Stranger 2012-04-04 17:08
Ads