php concatenating string math operation

这一生的挚爱 提交于 2019-12-24 02:32:29

问题


$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.


回答1:


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



回答2:


It's happening because 'hello' . 3 is avaluated as 0 when followed with math + operation.

when using brackets the sum is evaluated first and then the number is converted to string and concatenated with 'hello'




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/9092933/php-concatenating-string-math-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!