PHP – Understanding and Validating Integers

Nov 20, 2013, by admin

We have often issues with the validation of integers. As PHP has it’s own functions such as is_int() or is_integer() for validating integers,  but sometimes these functions works and sometimes not.  Actually this is due to difference between integers and string type in PHP. So here we 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:

<?php
    $num1=’25′;
    $num2=25;
    ?>

As we see above, $num1 is string and $num12 is a integer and that’s what does matter in PHP. Now, let’s try is_int() to validate the integers in PHP.

<?php
    echo is_int($num1); //returns false
    echo is_int($num2); //return true
    ?>

If you try to validate above variable $num1 using is_int() then it won’t work as it’s string type and returns false. Also when values posted from the form’s element can’t be other than string.

How to validate integers in PHP?

You can use regular expression to check weather posted values or variable contains the integers only or not. But the best solution is to use PHP function ctype_digit(). The ctype_digit() function checks if all of the characters in the provided string, text, are numerical. So If you try using ctype_digit($num1) then It will just give you the desired result.