Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## concatenate string sintax

Hello, I know it's wrong and to make it work i must use parenthesis but why in this code php shows \$b instead of \$a?
Isn't \$a nearer than \$b?

PHP Code:
<?php
function sum(\$a,\$b)
{
return
"Sum is "\$a+\$b;
}
echo
sum(20.12);
?>>
Thank you!

• Originally Posted by paperino00
Hello, I know it's wrong and to make it work i must use parenthesis but why in this code php shows \$b instead of \$a?
Isn't \$a nearer than \$b?

PHP Code:
<?php
function sum(\$a,\$b)
{
return
"Sum is "\$a+\$b;
}
echo
sum(20.12);
?>>
Thank you!
+ has a higher president than . has. Your equation becomes: ("Sum is " . \$a) + \$b, and since casting that string to an integer will result in 0, you have 0 + 0.12. This is why brackets are required in order to evaluate the terms as \$a + \$b and then concatenate the results.

• Originally Posted by Fou-Lu
+ has a higher president than . has.
actually, no. they have the same precedence (I know it’s a difficult word) [ref.].

Originally Posted by Fou-Lu
Your equation becomes: ("Sum is " . \$a) + \$b
you are contradicting yourself here (the original statement would resolve to "Sum is " . (\$a + \$b)), despite being correct.

• Your right, it is equal in precedence, and I did biff the whole explanation. My bad.

The precedence equal with a left associativity. So it evaluates left to right providing the . with a higher priority than the + in this context. So it does still resolve to ("Sum is " . \$a) + \$b.
As Dormilich mentioned, if the + had actual higher priority then it would evaluate the result of the \$a + \$b before the concat.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•