Thursday, April 21, 2011

String conversion to numbers

I came across the PHP documents today on Type Juggling and String conversion and find this interesting behavior.

$result = 10 + "10 pigs";  // integer(20);
$result1 = "10.0 people" + 10';  // float(20.0);

The "+" sign is an automatic type conversion operand.  Just like the example above, it doesn't care if you have non-numeric string inside your "string", it will convert to numbers for you.  The catch is, the number in a string must be occurred first, it won't work if the numeric value sits in the middle of the string.

According to the PHP document,
A valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

For further readings, here are the links:



No comments:

Post a Comment