Why is '…' concatenating two numbers in my

2019-02-12 03:16发布

问题:

I have the following code snippet where I don't really understand its output:

echo 20...7;

Why does this code output 200.7?

From what I know ... is the splat operator, which it is called in ruby, that lets you have a function with a variable number of arguments, but I don't understand what it does here in the context with echo.

Can anyone explain what exactly this code does?

回答1:

No this is not the splat/unpacking operator, even thought it might seem like it is. This is just the result of the PHP parsing process. Already writing your code a bit different might clear some confusion:

echo  20.           .           .7;
#       ↑           ↑           ↑
#    decimal  concatenation  decimal
#      dot         dot         dot

Now you have to know that .7 is 0.7 and you can omit the 0 in PHP as described in the syntax for float numbers:

DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)

So PHP just concatenates those two numbers together and while doing this PHP's type juggling will silently convert both numbers to strings.

So in the end your code is equivalent to:

echo "20" . "0.7";
//Output: "200.7"


标签: php numbers echo