- Instant help with your Php coding problems

Convert PHP string to int value

Sometimes it is important to have the value of a variable in int format. For example, if your visitors fill out a form with the age field which should be an int. However, in the $_POST array you get it as a string.


To convert a PHP string to int is quite easy. We need to use typecasting. So you need to use (int) before your variable. Here is an example of how to do this:

<?php
   $str = "10";
   $num = (int)$str;
?>

To check if the code really works we can use the === operator. This operator checks not only values but types as well. So the code should look like this:

<?php
   $str = "10";
   $num = (int)$str;
 
   if ($str === 10) echo "String";
   if ($num === 10) echo "Integer";
?>

One more question is open. What happens if our string is not a pure number string. I mean there are other characters as well in the string. In this case, the cast operation tries the best and can cast the string if only spaces are there or if the not valid characters are after the number value. It works as follows:

  • "10" -> 10
  • "10.5" -> 10
  • "10,5" -> 10
  • "10  " -> 10
  • "  10  " -> 10
  • "10test" -> 10
  • "test10" -> 0

Share "Convert PHP string to int value" with your friends