Understanding and Validating Integers in PHP

Advertisement

I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering why is_int() or is_integer() functions of PHP sometimes works and sometimes won’t.

If you become clear with the concept of integer and string in PHP then you’ll obviously come to know that why those functions are not working sometime to validate integers in PHP. Let’s look at this by an example

$a='10';
$b=10;

As you can see above, $a is string and $b is a integer and thats what does matter in PHP. Now, let’s try is_int() to validate the integers in PHP.

echo is_int($a); //returns false
echo is_int($b); //return true

And many of the PHP programmers tries to validate the posted values such as is_int($_POST['quantity']) and it just returns the false values although there are only digits in posted quantity.Why it is so? Because, $_POST['quantity'] is just a string and nothing more than a string. Values posted from the form’s element can’t be other variable type than string.

How to validate integers (digits) in PHP?

We can use regular expression to check weather posted value contains the integers only or not. But the regular expression might be a tedious task for people who are not good in using regular expression.

The best solution is using a function called ctype_digit() available in PHP. It just check weather the strings contains only digits or not. If you try using ctype_digit($_POST['quantity']) then It will just give you the desired result. But one thing you keep in mind that “ctype_digit()” is character type function the supplied parameter must be a string to get the proper result. And you can use “strval()” function available in PHP to convert any other data type to string in PHP

Tags:

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

5 Comments on “Understanding and Validating Integers in PHP”

  • Shafiq Rehman wrote on 6 May, 2008, 12:50

    If you are using ctype_digit() function to validate integer values you must keep in mind that it will return true when you pass ZERO (0) to it.

    Check the different behaviors of this function

    ctype_digit(‘0′); // return true
    ctype_digit(0); // return false
    ctype_digit(‘1′); // return true
    ctype_digit(1); // return false

  • Roshan wrote on 6 May, 2008, 16:36

    Thanks for heads up shafiq….I’ve mentioned it in the post

  • Suresh wrote on 12 May, 2008, 19:10

    thanxs

  • Manoj wrote on 12 April, 2010, 9:59

    i always suspect for validate integer value but now i am sure how to validate integer value.
    Thanks all

  • manikantan.v.r wrote on 23 June, 2011, 10:11

    easy to understand thanks

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.