PHP string to int

Home - Tutorials - Basics

This small tutorial shows you how to convert PHP string to int value.

Tutorial info:

Name:PHP string to int
Total steps:1

Bookmark PHP string to int

Bookmark and Share

Step 1 - Convert PHP string to int value

PHP string to int


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:

  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:

  1. <?php
  2. $str = "10";
  3. $num = (int)$str;
  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:


Tags: php string to int, string to int, string int

PHP string to int - Table of contents
Step 1 - Convert PHP string to int value

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.0144