Monday, 24 November 2014

PHP string to int

Step 1 - Convert PHP string to int value



Sometimes it is important to have the value of a variable in int format. For eaxmple 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 type casting.So you need to use (int) before your variable. Here is an example how to do this:
Code:
  1. <?php
  2. $str = "10";
  3. $num = (int)$str;
  4. ?>
To check if the code realy works we can use the === operator. This operator checks not only values but types as well. So the code should look like this:
Code:
  1. <?php
  2. $str = "10";
  3. $num = (int)$str;
  4.  
  5. if ($str === 10) echo "String";
  6. if ($num === 10) echo "Integer";
  7. ?>
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

0 comments:

Post a Comment