Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is '...' concatenating two numbers in my code?

Tags:

php

echo

numbers

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?

like image 971
Daniel Bejan Avatar asked May 17 '17 11:05

Daniel Bejan


1 Answers

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"
like image 118
YvesLeBorg Avatar answered Oct 22 '22 12:10

YvesLeBorg