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

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.