I'm currently learning PHP from a HTML, CSS, and JS background and I came across some unexpected behavior that interested me. Consequently, I experimented with the following code.
It seems that when written the return statement is written like this, everything before the arithmetic is removed/not rendered.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
17<br>
21<br>
However, when I change the first variable/parameter from $num
to $num2
, it seems that every between the first variable and the +
operator is removed.
Code:
<?php
function add($num, $num2) {
return $num2."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
14<br>
2<br>
After trying it in JS, I realized that putting brackets around the arithmetic equation would output the expected result.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".($num + $num2)."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
10+7 = 17<br>
20+1 = 21<br>
(Also making a $sum
variable would fix the problem)
My question is what causes the unexpected behavior by not putting the brackets around the equation?
The behavior you are seeing is the result of "type juggling".
Because PHP is not strictly-typed, a string can be interpreted as an integer when needed (or assumed to be needed by the interpreter), or vice versa. So the data type is converted, and if you're not careful can cause issues. In many other languages you would get an error if you treated a string like an integer or an integer like a string. JavaScript, for example, has String.parseInt()
to explicitly change the type.
What the interpreter is doing is roughly the following, step-by-step:
$num
- establish an integer with value 10
10."+"
- concatenating an integer with a string
10
becomes "10"
), and append a plus sign"10+"
"10+".$num2
- concatenating a string with an integer
"10+7"
"10+7"." = "
- concatenating 2 strings"10+7 = "
"10+7 = ".$num
- concatenating a string with an integer"10+7 = 10
"10+7 = 10" + $num2
- arithmetic calculation between a string and an integer"10+7 = 10"
pulls out the 10, then hits the +
and stops looking for numbers.17
;17."<br>"
- concatenation of an integer and a string<br>
17<br>
.For reference:
How does PHP know that you don't want to take this $num."+".$num2." = ".$num
and arithmetically add it to this $num2."<br>"
? It doesn't, unless you use parentheses to cause the $num + $num2
to happen first.
In the first example:
$num."+".$num2." = ".$num
Equates to the string: 10+7=10
, and then:
$num2
Equates to 7
.
When you attempt to add them +
the string 10+7=10
must be cast to an integer 10
and and when added to 7
gives you 17
then the string <br>
is concatenated.
See PHP: String Conversion to Numbers
With parentheses:
$num."+".$num2." = ".($num + $num2)."<br>";
You get string 10+7=
concatenated with 10+7
(17
) concatenated with string <br>
.