Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP concatenation of strings and arithmetic operations

I started learning PHP not too long ago and I ran into this issue:

<?php

$a = 1;
$b = 2;

echo "$a * $b  = " . $a * $b;
echo "<br />";

echo "$a / $b  = " . $a / $b;
echo "<br />";

echo "$a + $b  = " . $a + $b;
echo "<br />";

echo "$a - $b  = " . $a - $b;
echo "<br />";

I get the following output:

1 * 2 = 2
1 / 2 = 0.5
3
-1

The last two lines in the output are not what I would expect.

Why is this? How are these expressions evaluated? I'm trying to get a better understanding of the language.

like image 490
sebastian Avatar asked Aug 16 '12 18:08

sebastian


1 Answers

This is happening because the concatenation operator has a higher precedence than the addition or subtraction operators, but multiplication and division have a higher precedence then concatenation.

So, what you're really executing is this:

echo ("$a + $b  = " . $a) + $b;
echo ("$a - $b  = " . $a) - $b;

In the first case, that gets turned into this:

"1 + 2 = 1" + $b

Which PHP tries to convert "1 + 2 = 1" into a number (because of type juggling) and gets 1, turning the expression into:

1 + 2

Which is why you get 3. The same logic can be applied to the subtraction condition.

Instead, if you put parenthesis around the calculations, you'll get the desired output.

echo "$a + $b  = " . ($a + $b);
echo "$a - $b  = " . ($a - $b);
like image 172
nickb Avatar answered Sep 17 '22 23:09

nickb