What is the best way of checking if input is numeric?
- 1-
- +111+
- 5xf
- 0xf
Those kind of numbers should not be valid. Only numbers like: 123, 012 (12), positive numbers should be valid. This is mye current code:
$num = (int) $val;
if (
preg_match('/^\d+$/', $num)
&&
strval(intval($num)) == strval($num)
)
{
return true;
}
else
{
return false;
}
filter_var()
For PHP version 4 or later versions:
ctype_digit
was built precisely for this purpose.I use
to validate if a value is numeric, positive and integral
http://php.net/is_numeric
I don't really like ctype_digit as its not as readable as "is_numeric" and actually has less flaws when you really want to validate that a value is numeric.