7

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.

1
  • As a general guideline, you probably shouldn't rely on PHP's weak typing anyways. Commented Aug 16, 2012 at 18:32

3 Answers 3

9

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Another solution is to not concatenate, but use multiple arguments in the call to echo. echo "$a + $b = ", $a + $b;
It's always seemed to me to be really illogical to give half of the operators higher precedence than concatenation, and half of them lower precedence... Does anyone know why this is the case? Is it just bad design or is there a reason for it??
1

Concatenation takes precedence over addition and subtraction, but not multiplication or division. So

echo "$a + $b  = " . $a + $b;

is equivalent to

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

And PHP disregards the first part, as it is difficult to convert it into a number, leaving you with just the + $b.

If you use parentheses, you should be fine.

Comments

0

Well, you have found really weird behavior, but :)

From the from the arithmetic operators, division and multiplication have highest precedence, so they are evaluated before the concatenation.

While the addition and extraction have lower precedence, so first the left part is evaluated and then added/extracted to the right part. But PHP tries to extract the numeric value out of the string and only the first char is such, so it does that with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.