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.
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.
string
containing 3 characters "100" and we cast it to an int
with the int
cast. This gives us the int
100.string
"100", the string
is converted to 100.string
does not contain digits, using the int
cast will return the int
value 0.intval()
function instead of an int
cast to perform the string
to int
conversion.float
cast can parse strings containing floats.string
with is_numeric
, which will tell us whether the int
cast is appropriate to use.// 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.