...

# concatenate string sintax

paperino00
04-19-2012, 10:44 PM
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
function sum(\$a,\$b)
{
return "Sum is ". \$a+\$b;
}
echo sum(2, 0.12);
?>>

Thank you!

Fou-Lu
04-19-2012, 11:41 PM
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
function sum(\$a,\$b)
{
return "Sum is ". \$a+\$b;
}
echo sum(2, 0.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.

Dormilich
04-20-2012, 07:56 AM
+ has a higher president than . has.
actually, no. they have the same precedence (I know it’s a difficult word) [ref. (http://www.php.net/manual/en/language.operators.precedence.php)].

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.

Fou-Lu
04-20-2012, 03:43 PM
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.