PHP string number concatenation messed up PHP string number concatenation messed up php php

PHP string number concatenation messed up


That's strange...

But

<?php    echo '11hello ' . (1 + 2) . '34';?>

or

<?php    echo '11hello ', 1 + 2, '34';?>

fixes the issue.


UPDATE v1:

I finally managed to get the proper answer:

'hello' = 0 (contains no leading digits, so PHP assumes it is zero).

So 'hello' . 1 + 2 simplifies to 'hello1' + 2 is 2. Because there aren't any leading digits in 'hello1' it is zero too.


'11hello ' = 11 (contains leading digits, so PHP assumes it is eleven).

So '11hello ' . 1 + 2 simplifies to '11hello 1' + 2 as 11 + 2 is 13.


UPDATE v2:

From Strings:

The value is given by the initial portion of the string. If the stringstarts with valid numeric data, this will be the value used.Otherwise, the value will be 0 (zero). Valid numeric data is anoptional sign, followed by one or more digits (optionally containing adecimal point), followed by an optional exponent. The exponent is an'e' or 'E' followed by one or more digits.


The dot operator has the same precedence as + and -, which can yield unexpected results.

That technically answers your question... if you want numbers to be treated as numbers during concatenation, just wrap them in parentheses.

<?php    echo '11hello ' . (1 + 2) . '34';?>


You have to use () in a mathematical operation:

echo 'hello ' . (1 + 2) . '34'; // output hello334echo '11hello ' . (1 + 2) . '34'; // output 11hello334