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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With