Reputation: 159
In PHP, "aaa" + "bbb"
would produce 0
.
I know that to concatenate two strings in PHP, I need to use .
. But I don't know why does addition +
of two strings in PHP produce this result?
Upvotes: 8
Views: 208
Reputation: 79004
When you use arithmetic operators on non-numbers then PHP casts them to integer type. PHP is sort of smart, so string "1"
would be cast to integer 1
and string "1.0"
would be cast to float, however "aaa"
would be cast to integer 0
, as well as "bbb"
. So both cast to 0
is 0 + 0
which obviously is 0
.
See PHP: String conversion to numbers.
As of PHP 7.1.0 this generates:
Warning: A non-numeric value encountered
However, this is fine since they are numeric though not a numeric type (strings):
var_dump("1" + "2");
Upvotes: 7