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
Category:Basics
Date:2007-09-05
Product:See complete product

Bookmark PHP string to int



AddThis Social Bookmark Button

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:

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:


 







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

F1 Site Family
AJAX F1
CSS F1
Database F1
Forex F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Windows F1
 
vpsnoc
 
MaxTutorial
Monthly mortgage payment calculator
WebFormGenerator
Forex mini accounts

Total time: 0.0255