Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple arithmetic in PHP

Tags:

php

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
like image 891
Stranger Avatar asked Apr 04 '12 16:04

Stranger


1 Answers

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.

like image 77
Jon Avatar answered Sep 28 '22 02:09

Jon