80

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;
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
medusa1414
  • 1,139
  • 1
  • 9
  • 14
  • don't make (int) on 1st line in your code! transform it to (string) then work with strings with ctype_digit($num) will do better than int(proff in manual http://php.net/ctype_digit) !!! – Vladimir Ch Jan 10 '17 at 04:04

6 Answers6

80

ctype_digit was built precisely for this purpose.

46

I use

if(is_numeric($value) && $value > 0 && $value == round($value, 0)){

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.

Mathieu Dumoulin
  • 12,126
  • 7
  • 43
  • 71
  • 6
    except that the OP is looking for positive integers only, not numerics. –  Jul 10 '12 at 17:23
20

filter_var()

$options = array(
    'options' => array('min_range' => 0)
);

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 5
    +1 As this is a more semantic (though more verbose) solution than `ctype_digit` –  Jul 10 '12 at 17:24
11
return ctype_digit($num) && (int) $num > 0
j0k
  • 22,600
  • 28
  • 79
  • 90
11

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";
}
?>
1

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;
}
Kareem
  • 5,068
  • 44
  • 38
  • This doesn't work, for example OP's example of "1-" shouldn't be considered a valid number, but according to this regex it is. – rowatt Oct 13 '19 at 07:24
  • @rowatt the \- is for negative numbers. I changed it to only account for "-" at the begging – Kareem Oct 14 '19 at 01:16