Reputation: 1169
What is the best way of checking if input is numeric?
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;
}
Upvotes: 83
Views: 150845
Reputation: 5404
The most secure way
if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
//if all made of numbers "-" or ".", then yes is number;
}
Upvotes: 1
Reputation: 998
For PHP version 4 or later versions:
<?PHP
$input = 4;
if(is_numeric($input)){ // return **TRUE** if it is numeric
echo "The input is numeric";
}else{
echo "The input is not numeric";
}
?>
Upvotes: 12
Reputation: 12244
I use
if(is_numeric($value) && $value > 0 && $value == round($value, 0)){
to validate if a value is numeric, positive and integral
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.
Upvotes: 46
Reputation: 219794
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
Upvotes: 21