The question checks your knowledge of two aspects of language: how PHP treats strings within a mathematical operation - that is, how the cast of string for a number - and the precedence of operators.
The first aspect was commented on in the other answers and is very well discussed in:
Why in PHP the expression "2 + '6 apples'" is 8?
In short, when evaluating a string To convert it to a numeric value, PHP will check the contents from left to right. If the first characters are a valid numeric value, then it is kept as a result. If it is not a valid value, the return will be 0.
var_dump((float) "1foo"); // float(1)
var_dump((float) "1.9foo"); // float(1.9)
var_dump((float) "foo3.14"); // float(0)
The second aspect, not cited in the other answers and fundamental for the correct analysis is the operators' precedence. The operators used are the concatenation, .
, and the addition, +
. When checking the operator precedence table in the documentation:
Note that both operators have the same precedence, so the expression will be analyzed from left to right, operator to operator.
'hello'. 1 + 2 .'34';
- The first operator is concatenation, then the value is generated
'hello1'
;
- The second operator is of addition, then the value
'hello1'
is first evaluated as numerical, returning 0, being added with 2, resulting in 2;
- The third operator is concatenation, so the value is generated
'234'
;
This process is evident when assessing the opcodes generated by VLD:
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
3 0 E > ADD ~0 'hello1', 2
1 CONCAT ~1 ~0, '34'
2 ECHO ~1
3 > RETURN 1
Note that for PHP, the first operation will occur even before the expression is evaluated; this is because both operators are constant.
According to the website 3v4l.org, the same output is generated in all tested versions, although only in versions higher than 7.1 an alert is issued on the conversion of a string nonnumerical.
To demonstrate how the precedence of operators is important in this case, simply replace the addition by division. According to the precedence table, the division has a precedence greater than the concatenation, so it will be evaluated before. See:
echo 'hello'. 1 / 2 .'34'; // Resultará: hello0.534
This is why when evaluating the expression, the division will be executed before, returning the value 0.5
, and after, the two concatenations will be executed, returning hello0.534
.
is on my end with
PHP 7.0
and I get the error:PHP Parse error: syntax error, unexpected '.1' (T_DNUMBER), expecting ',' or ';' in php shell code on line 1
– RFL
This error code there due to lack of spaces.
– rray
Sorry for the lack of spaces. I forgot to put
– DNick