Arithmetic in concatenating strings without parentheses produces a strange result

Consider the following line of code:

<?php $x = 10; $y = 7; echo '10 - 7 = '.$x-$y; ?> 

The result of this is 3, which is the expected result of computing $ x- $ y. However, the expected result:

10 - 7 = 3

So my question is what happened to the string that I am concatenating with the calculation? I know that to get the expected result, I need to enclose the arithmetic operation in brackets:

 <?php $x = 10; $y = 7; echo '10 - 7 = '.($x-$y); ?> 

exits

10 - 7 = 3

But since PHP does not complain about the source code, I can only ask what is the logic of the products in this case? Where did the string go? If anyone can explain this or point me to a place in the PHP manual where this is explained, I would appreciate it.

+4
source share
3 answers

Your string '10 - 7 = ' combined with $x . This is then interpreted as int , which leads to 10 , and then 7 is subtracted, which leads to 3 .

For more information, try the following:

 echo (int) ('10 - 7 = ' . 10); // Prints "10" 

More information on converting strings to numbers can be found at http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

If the string starts with valid numeric data, this will be the value used

+4
source

In this code:

 echo '10 - 7 = '.$x-$y; 

Concatenation takes precedence, so you are left with this:

 echo '10 - 7 = 10'-$y; 

Since this is trying to do integer subtraction with a string, the string is first converted to an integer, so you have something like this:

 echo (int)'10 - 7 = 10'-$y; 

The integer value of this string is 10 , so the resulting arithmetic is as follows:

 echo 10-$y; 

Since $y - 7 and 10 - 7 = 3 , the result will be an echo: 3 .

+4
source

. and - have the same precedence , so PHP interprets '10 - 7 = 10' as a number, giving 10 , and subtracting 7 gives 3 .

+2
source

All Articles