Convert string to int in PHP

Here’s another quick tip.  If you have an integer value stored as a string and want to convert it to an “int” type, this tip is for you.  You might want to use this if you’ve read an integer from a text file and therefore it was read in as a string value, but now you want to do a numeric comparison.  Anyways, on to the tip.  The following code converts a the string “25” to integer format.

$int_as_string = "25";

$int_value = intval($int_as_string);

if($int_value === 25) {
   print "It worked!";
} else {
   print "It didn't work!";
}

As you can imagine, the code above prints “It worked!”.  The key function here is “intval” which takes a string as an argument and converts it to a integer value.  If the function can’t convert it to an integer (like if you ran intval(‘hello’)), the function returns zero.

Hope you enjoyed this quick tip showing you how to convert a string to int in PHP.  Thanks for reading.

2 thoughts on “Convert string to int in PHP”

Leave a Comment