PHP string concatenation and arithmetic

I started learning PHP not so long ago, and I ran into this problem:

<?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 expect.

Why is this? How are these expressions evaluated? I'm trying to better understand the language.

+6
source share
3 answers

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

So what are you really doing:

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

In the first case, it turns into this:

 "1 + 2 = 1" + $b 

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

 1 + 2 

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

Instead, if you place the brackets around the calculations, you get the desired result.

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

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

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

equivalently

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

And PHP ignores the first part, since it's hard to convert it to a number, leaving you only + $b .

If you use parentheses, you should be fine.

+1
source

Well, you found really strange behavior, but :)

Of the arithmetic operators, division and multiplication have the highest priority, so they are calculated before concatenation.

While adding and extracting have a lower priority, therefore, the left part is processed first, and then added / extracted to the right part. But PHP is trying to extract a numeric value from a string, and only the first char is like that, so it does it with it.

0
source

Source: https://habr.com/ru/post/923061/


All Articles