Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operation within string concatenation without parenthesis causes strange result

Consider the following line of code:

<?php
$x = 10;
$y = 7;

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

The output of that is 3, which is the expected result of the calculation $x-$y. However, the expected output is:

10 - 7 = 3

My question therefore is, what happened to the string that I'm concatenating with the calculation? I know that in order to produce the result I expected, I need to enclose the arithmetic operation in parenthesis:

<?php
$x = 10;
$y = 7;

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

outputs

10 - 7 = 3

But since PHP does not complain about the original code, I'm left wondering what the logic behind the produced output in that case is? Where did the string go? If anyone can explain it or point me to a location in the PHP manual where it is explained, I'd be grateful.

like image 375
Jens Wegar Avatar asked Dec 27 '22 13:12

Jens Wegar


2 Answers

Your string '10 - 7 = ' is being concatenated with $x. Then that is being interpreted as an int which results in 10 and then 7 is subtracted, resulting in 3.

For more explanation, try this:

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

More information on string to number conversion 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

like image 52
Rusty Fausak Avatar answered Jan 05 '23 15:01

Rusty Fausak


In this code:

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

The concatenation takes precedence, so what you're left with is this:

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

Because this is trying to perform integer subtraction with a string, the string is converted to an integer first, so you're left with something like this:

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

The integer value of that string is 10, so the resulting arithmetic looks like this:

echo 10-$y;

Because $y is 7, and 10 - 7 = 3, the result being echoed is 3.

like image 30
FtDRbwLXw6 Avatar answered Jan 05 '23 15:01

FtDRbwLXw6