Strings can be converted and parsed into their numerical values in PHP simply by using them within a mathematical context. PHP will determine the appropriate numerical data type upon conversion. If the number is small enough, it will be converted into an integer data type. If it is larger or contains decimal or scientific notation, then it will be converted into the float data type, which combines the roles for the long, double and float data types in C and Java.
Open a text editor and immediately save with the name "longParse.php."
Paste the following code to assign a string to a variable named "$str":
$astring = "100";
Paste the following to convert that string to an integer and add 1 to it:
$anumber = $astring + 1;
Because the string is being used in a mathematical context and contains information that can be understood as a number, PHP will convert it automatically to the appropriate numerical type (in this case an integer because the number is so small) and continue forward. This can feel uncomfortable for programmers who want more precise control over the resulting data, so it is possible to explicitly perform the conversion using a cast command.
Paste the following to explicitly cast the string into either an integer or a float:
$anumber = (int) $astring; $anumber = (float) $astring;
If you are certain that the numbers are relatively small and will never contain decimals, you should use "int," as it saves memory. However, if you think the numbers may be quite large or contain decimals, you should use "float."