15

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?

4

5 回答 5

16

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

于 2013-04-30T07:53:21.263 回答
6

点运算符与 and 具有相同的优先级,这可能会产生意想不到的结果。+-

从技术上讲,这回答了您的问题……如果您希望在连接期间将数字视为数字,只需将它们括在括号中即可。

<?php
    echo '11hello ' . (1 + 2) . '34';
?>
于 2013-04-30T07:57:32.907 回答
5

You have to use () in a mathematical operation:

echo 'hello ' . (1 + 2) . '34'; // output hello334
echo '11hello ' . (1 + 2) . '34'; // output 11hello334
于 2013-04-30T07:53:48.167 回答
1

如果您讨厌将运算符放在两者之间,请将它们分配给一个变量:

$var = 1 + 2;

echo 'hello ' . $var . '34';
于 2013-04-30T07:56:10.820 回答
1

您应该检查PHP 类型转换表以更好地了解幕后发生的事情。

于 2013-04-30T07:54:41.947 回答