What happens in 1 ... 1 in PHP?

26

On the web I came across the following code snippet:

echo 1...1;

Resulting in 10.1 . I made the var_dump of it and the return is:

string(4) "10.1"

Works with variable assignment:

$x = 1...1;
echo $x; // 10.1

And for other values:

echo 2...2; // 20.2
echo 1...1; // 10.2
echo 3...2; // 30.2

I know that in PHP 5.6+ there is the operator ... ( splat operator ), which extracts the values of an array - similar to * of Python - but it does not seem to be the case, why, according to the site 3V4L , the result is the same since version 4.3.0, that there was no such operator.

Apparently it only works with integers.

Would it be some implicit concatenation of values that PHP does?

    
asked by Anderson Carlos Woss 30.05.2017 в 14:31
source

1 answer

35

In fact, what happens is the concatenation of values of type float . PHP parses 1. to be float(1.0) and .1 to be float(0.1) , in this way, concatenation of float(1.0) . float(0.1) happens, however, since 1.0 is integer, PHP retains only 1 .

1. . .1
|  |  |
|  |  +--- Analisado como float 0.1
|  +--- Operador de concatenação de string, faz o cast dos operandos para string
+--- Analisado como float 1.0, feito o cast para int

That is, to do:

echo 1...1;

It's the same as:

echo (1.).(.1);

So much so that you can add the decimal part of the first value:

echo 5.32..7; // 5.320.7

But it is not possible to add an integer part to the second value:

echo 3..5.67; // Syntax error

Only if you insert the parentheses correctly:

echo 3..(5.67); // 35.67

Or if you enter spaces between operators:

echo 3. . 5.67; // 35.67

Using space you can define both the decimal part of the first value and the integer part of the second:

echo 3.14 . 1.41; // 3.141.41

Summary of the opera

I ran a series of tests and the result is below. I did not include situations that would cause syntax error.

1...1        = 10.1
2...2        = 20.2
10...10      = 100.1
(1.).(.1)    = 10.1
1. . .1      = 10.1
5.32..7      = 5.320.7
3..(5.67)    = 35.67
3. . 5.67    = 35.67
3.14 . 1.41  = 3.141.41

According to the tests in 3V4L , the output is the same since version 4.3.0:

    
answered by 30.05.2017 / 14:50
source