Adding Two Numeric Strings Actually Works? Why?

Why do the following lines of code return 5 in PHP 5.3?

$ReturnValue = "2" + "3";
echo $ReturnValue;
$ReturnValue = "2 v" + "3";
echo $ReturnValue;

Shouldn’t it return an error? I thought strings couldn’t be added until they were cast as integers? Anyone care to explain why it’s working fine?

I believe it is probably to make it easier on developers, so that you can pull integers from files or databases (default return values are strings) and not have to force them as integers. The “2 v” example is probably another usability thing - so that you can make calculations with measurements such as “2cm” + “4cm” or anything else of the sort. It just pulls what it can from the string and stops at the first non-integer character as far as I’m aware.

Sponsor our Newsletter | Privacy Policy | Terms of Service