php string number concatenation messed up

2019-01-15 18:26发布

I got some php code here:

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

which outputs 234,

but when I add a number 11 before "hello":

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

It outputs 1334 rather than 245(which I expected it to), why is that?

5条回答
混吃等死
2楼-- · 2019-01-15 18:59

you have to use () in mathematical operation

echo 'hello ' . (1 + 2) . '34'; // output hello334
echo '11hello ' . (1 + 2) . '34'; // output 11hello334
查看更多
放荡不羁爱自由
3楼-- · 2019-01-15 19:05

That's strange...

But

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

OR

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

fixing issue.


UPDv1:

Finally managed to get 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 no leading digits in 'hello1' 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.


UPDv2:

http://www.php.net/manual/en/language.types.string.php

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

查看更多
我命由我不由天
4楼-- · 2019-01-15 19:07

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 concatination just wrap them in parenthesis.

<?php
echo '11hello ' . (1 + 2) . '34';
?>
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-15 19:10

If you hate putting operators in between assign them to vaiable

$var = 1 + 2;

echo 'hello ' . $var . '34';
查看更多
SAY GOODBYE
6楼-- · 2019-01-15 19:15

You should check PHP type conversion table to get better idea what's happen behind the scenes: http://php.net/manual/en/types.comparisons.php

查看更多
登录 后发表回答