Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to add parentheses to + - operations when concatenating?

I was writing a small program when I encountered something strange. If I wanted PHP to present an arithmetic operations of addition or subtraction with an echo statement and the outcome of the operation I had to add parentheses or the html page wouldn't present the operation but just the outcome.

Below is a reduced example.

first case (without parentheses):

$a = 10;
$b = 5;
echo "$a + $b = ".$a + $b."<br>"; // 15
echo "$a - $b = ".$a - $b."<br>"; // 5
echo "$a * $b = ".$a * $b."<br>"; // 10 * 5 = 50
echo "$a / $b = ".$a / $b."<br>"; // 10 / 5 = 2
echo "$a % $b = ".$a % $b."<br>"; // 10 % 5 = 0

second case (with parentheses):

$a = 10;
$b = 5;
echo "$a + $b = ".($a + $b)."<br>"; // 10 + 5 = 15
echo "$a - $b = ".($a - $b)."<br>"; // 10 - 5 = 5
echo "$a * $b = ".($a * $b)."<br>"; // 10 * 5 = 50
echo "$a / $b = ".($a / $b)."<br>"; // 10 / 5 = 2
echo "$a % $b = ".($a % $b)."<br>"; // 10 % 5 = 0

Could anyone explain why this is happening?

like image 964
Tim8288 Avatar asked Sep 26 '22 12:09

Tim8288


1 Answers

from link by Mark Baker you can see that

Addition, subtraction, and string concatenation have equal precedence!

in echo "$a + $b = ".$a + $b."<br>"; //15

Concatenate the first string literal and the value of $a, then implicitly convert that to a number (10) so you can add $b to it, then concatenate the final string literal.

when you put it in brackets, the addition is treated as number(15) therefore no mathematical operations with string

like image 161
Pepo_rasta Avatar answered Oct 13 '22 00:10

Pepo_rasta