Home » Php » Why does addition "+" of two strings in PHP produce this result?

Why does addition "+" of two strings in PHP produce this result?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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");