Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...