Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP is confused when adding and concatenating

I have the following code:

<?php

    $a = 1;
    $b = 2;

    echo "sum: " .  $a + $b;
    echo "sum: " . ($a + $b);

?>

When I execute my code I get:

2
sum: 3

Why does it fail to print the string "sum:" in the first echo? It seems to be fine when the addition is enclosed in parentheses.

Is this weird behaviour anywhere documented?

like image 426
aizquier Avatar asked May 31 '12 20:05

aizquier


People also ask

What is the difference between concatenation and addition?

Both addition and concatenation use the same + operator, but they are not same. Concatenation is used to concatenate i.e. add strings, whereas simple addition adds numbers.

Why is Javascript concatenating instead of adding?

The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.

How does concatenation work in PHP?

The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('. ='), which appends the argument on the right side to the argument on the left side.

What is an efficient way to combine two variables in PHP?

The concatenate term in PHP refers to joining multiple strings into one string; it also joins variables as well as the arrays. In PHP, concatenation is done by using the concatenation operator (".") which is a dot.


2 Answers

Both operators the addition + operator and the concatenation . operator have the same operator precedence, but since they are left associative they get evaluated like the following:

echo (("sum:" . $a) + $b);
echo ("sum:" . ($a + $b));

So your first line does the concatenation first and ends up with:

"sum: 1" + 2

(Now since this is a numeric context your string gets converted to an integer and thus you end up with 0 + 2, which then gives you the result 2.)

like image 195
mgibsonbr Avatar answered Oct 12 '22 10:10

mgibsonbr


If you look at the page listing PHP operator precedence, you'll see that the concatenation operator . and the addition operator + have equal precedence, with left associativity. This means that the operations are done left to right, exactly as the code shows. Let's look at that:

$output = "sum: " . $a;
echo $output, "\n";
$output = $output + $b;
echo $output, "\n";

This gives the following output:

sum: 1
2

The concatenation works, but you then try to add the string sum: 1 to the number 2. Strings that don't start with a number evaluate to 0, so this is equivalent to 0 + 2, which results in 2.

The solution, as you suggest in your question, is to enclose the addition operations in brackets, so they are executed together, and then the result of those operations is concatenated.

echo "sum: " . ($a + $b);
like image 43
lonesomeday Avatar answered Oct 12 '22 09:10

lonesomeday