How to Convert String to Long in PHP

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

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.

Advertisement

Step 1

Open a text editor and immediately save with the name "longParse.php."

Video of the Day

Step 2

Paste the following code to assign a string to a variable named "$str":

$astring = "100";

Advertisement

Step 3

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.

Advertisement

Advertisement

Step 4

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."

Video of the Day

Advertisement

Advertisement

references

Report an Issue

screenshot of the current page

Screenshot loading...