Home  >  Article  >  Backend Development  >  Why Does PHP Concatenation and Addition Lead to Unexpected Results?

Why Does PHP Concatenation and Addition Lead to Unexpected Results?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 10:50:29385browse

Why Does PHP Concatenation and Addition Lead to Unexpected Results?

Unveiling PHP's Ambiguity: The Curious Case of Concatenation and Addition

PHP's operator precedence and associativity can lead to unexpected results when both addition and concatenation operators are involved. Consider this code:

<code class="php">$a = 1;
$b = 2;

echo "sum: " .  $a + $b; // Output: 2
echo "sum: " . ($a + $b); // Output: sum: 3</code>

Why the discrepancy? It all comes down to PHP's operator evaluation order.

Both the addition ( ) and concatenation (.) operators have the same precedence, but they are left-associative. This means that when PHP encounters an expression involving multiple operators with the same precedence, it evaluates the leftmost operator first and works its way to the right.

In the first echo statement, the concatenation operator (.) evaluates first, resulting in the following:

"sum: 1" + 2

The string "sum: 1" is then converted to a numeric value (0) and added to $b (2), yielding the output of 2.

In the second echo statement, the parentheses force the addition operator to evaluate first:

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

The result is then concatenated with the string "sum:", yielding the desired output of "sum: 3".

This behavior is documented in PHP's documentation on Operator Precedence. It states that "Operators with the same precedence evaluate from left to right, i.e., first , then ., then -."

The above is the detailed content of Why Does PHP Concatenation and Addition Lead to Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn