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.
- Skill level:
- Moderately Easy
Other People Are Reading
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."
Tips and warnings
- You can find out the minimum and maximum values of the "int" data type for your system by using the command PHP_INT_MAX, but bear in mind that this will change depending on the operating system and environment where the program is run.
- If the values are likely to be extremely large, more than 1.8 x 10^308, then PHP provides a library that supports GMP numbers. These numbers are limited only by memory size on the system. Paste the following to create such a number:
- $a = gmp_init("123456");
- Because GMP is much slower than the primitive data types, it should not be used unless the programmer is certain such accuracy will be needed, but it is available.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for