$a = 'hello' . 3 + 6 + 10;
echo $a; // 16
I would expect it to be hello19 not 16.
I know I can put the math operation in ():
$a = 'hello' . (3 + 6 + 10);
echo $a; // hello19
But why is php returning 16?
Thank in advance.
In PHP both . and + have equal precedence and are both left associative.
As a result
'hello' . 3 + 6 + 10;
is evaluated as
('hello' . 3) + 6 + 10;
= 'hello3' + 6 + 10
= ('hello3' + 6) + 10 // String 'hello3' when interpreted as a number gives 0
// as it starts with a non-digit.
= 6 + 10
= 16
first look at this:
$a = 'hello' . 3;
echo (int)$a; //echoes 0
that's because hello3 starts with a letter but not a digit and php casts it to integer as zero. so 0+6+10 is obvious 16.
the second code first computes 3 + 6 + 10 in braces and then conctenates hello with the result which is 19
Following PHP's operator precedence and associativity you can rewrite your expression to an equivalent expression as follows:
'hello' . 3 + 6 + 10; <==>
('hello' . 3) + 6 + 10; <==>
((('hello' . 3) + 6) + 10);
And if we evaluate that expression, as PHP would:
((('hello' . 3) + 6) + 10); =
(('hello3' + 6) + 10); =
((0 + 6) + 10)); =
(6 + 10); =
16