Home
PHP
Parse: Convert string to int
This page was last reviewed on May 29, 2023.
Dot Net Perls
Parse, int. In real-world PHP programs we will often end up with a string containing digits in the form of a number. These strings are not ints, but can be converted to ints.
With the int cast, we can directly perform this conversion. Other approaches, like intval, also work. And is_numeric can tell us whether the cast will succeed.
Example. This example performs string to integer conversions in a variety of ways. It uses casts, intval, and the is_numeric function to test string data.
Part 1 We have the string containing 3 characters "100" and we cast it to an int with the int cast. This gives us the int 100.
Part 2 Sometimes PHP will perform the conversion on its own (an implicit cast). If we add 1 to the string "100", the string is converted to 100.
Part 3 If our string does not contain digits, using the int cast will return the int value 0.
Part 4 We can use the intval() function instead of an int cast to perform the string to int conversion.
Part 5 Floats have a decimal place and contain fractional numbers. The float cast can parse strings containing floats.
Part 6 We can test our string with is_numeric, which will tell us whether the int cast is appropriate to use.
if
// Part 1: convert numeric string to int. $value = "100"; $test = (int) $value; var_dump($value, $test); // Part 2: add 1 to numeric string. $value = "200"; $test = $value + 1; var_dump($test); // Part 3: if not numeric string, casting to int returns 0. $value = "bird"; $test = (int) $value; var_dump($test); // Part 4: use intval to convert to integer. $value = "300"; $test = intval($value); var_dump($test); // Part 5: convert string to float. $value = "1.5"; $test = (float) $value; var_dump($value, $test); // Part 6: use is_numeric to determine if string is numeric, and then parse it. $value = "600"; if (is_numeric($value)) { $test = (int) $value; var_dump($test); }
string(3) "100" int(100) int(201) int(0) int(300) string(3) "1.5" float(1.5) int(600)
By using casts, we can change the type of strings to ints. If the cast does not succeed, the value 0 is returned—but we can use is_numeric to test for valid input.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 29, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.