The question checks your knowledge about two aspects of the language: how PHP treats strings within a mathematical operation - that is, how cast string to a number - and the precedence of the operators.
The first aspect was commented on in the other answers and is very well discussed in:
Why is the expression "2 + '6 apples'' equal to 8? p>
In short, when evaluating a string
to convert it to a numeric value, PHP will check content from left to right. If the first few 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 mentioned in the other answers and fundamental to the correct analysis is the precedence of the operators. The operators used are concatenation, .
, and addition, +
. When checking the operators precedence table in documentation :
Noticethatbothoperatorshavethesameprecedence,sotheexpressionwillbeparsedfromlefttoright,operatortooperator.
'hello'.1+2.'34';
Thefirstoperatorisconcatenation,sothevalue'hello1'
isgenerated;Thesecondoperatorisaddition,sothevalue'hello1'
isfirstevaluatedasnumeric,returning0,beingaddedwith2,resultingin2;Thethirdoperatorisconcatenation,sothevalue'234'
isgenerated;Thisprocessisevidentwhenevaluatingtheopcodesgeneratedby 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 site 3v4l.org , the same output is generated in all versions tested, although only in versions higher than 7.1 that a alert is issued on the conversion of a non-numeric string .
To demonstrate how operator precedence is important in this case, simply replace addition by division. According to the precedence table, the division has a higher precedence than the concatenation, so it will be evaluated first. See:
echo 'hello'. 1 / 2 .'34'; // Resultará: hello0.534
This is because by evaluating the expression, the division will be executed before, returning the value 0.5
, and after that, the two concatenations will be executed, returning hello0.534
.