Forum Moderators: coopster
For example i did a var_dump() on a post value and it came up
STRING("3");
if i did:
is_numeric($_POST[value]); //this returns a true because "3" is numeric
However if i did
is_int($_POST[value]); //this returns false
What is the fastest way to test a post/get value if its an integer?
Thanks,
Ryan
$pattern = "/^([0-9])+$/";
if(preg_match($pattern,$string)) {
echo 'good int';
} else {
echo 'not an int';
}
However, what you will notice is if you try to use an integer value outside of the following range on a 32-bit system:
-2147483648 to 2147483647
The intval() function will fail you. You see, anything over 10 digits (on 32 bit systems) is no longer an integer in PHP, it's a float. There is also a max range on 64-bit systems (see documentation references below).
Also be careful with is_int() [php.net]! You'll run into the same issues. More information on this can be found on the intval() [php.net] and the integer [php.net] pages.
What will work? Well, I ran into this a couple of years ago and have found the following function to be more reliable for validating integers:
function isValidInteger($i)
{
return (is_numeric($i) && !preg_match('/[[:^digit:]]/', $i) ? true : false);
}
<pre>
<?php
function CheckIsInt ($x)
{
return (is_numeric($x) ? intval($x)==$x : false);
}
function isValidInt($i)
{
return (is_numeric($i) && !preg_match('/[[:^digit:]]/', $i) ? true : false);
}
$integers = array(
123456789,
2147483647,
2147483648
);
foreach ($integers as $i) {
print 'isValidInt('.$i.'): ';
var_dump(isValidInt($i));
print 'CheckIsInt('.$i.'): ';
var_dump(CheckIsInt($i));
}
?>
<pre>
isValidInt(123456789): bool(true)
CheckIsInt(123456789): bool(true)
isValidInt(2147483647): bool(true)
CheckIsInt(2147483647): bool(true)
isValidInt(2147483648): bool(true)
CheckIsInt(2147483648): bool(false)