PHP: Best way to check if input is a valid number?

PhpInputValidationNumeric

Php Problem Overview


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;
}

Php Solutions


Solution 1 - Php

ctype_digit was built precisely for this purpose.

Solution 2 - Php

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.

Solution 3 - Php

filter_var()

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

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}

Solution 4 - Php

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

Solution 5 - Php

return ctype_digit($num) && (int) $num > 0

Solution 6 - Php

> 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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmedusa1414View Question on Stackoverflow
Solution 1 - Phpuser1479055View Answer on Stackoverflow
Solution 2 - PhpMathieu DumoulinView Answer on Stackoverflow
Solution 3 - PhpJohn CondeView Answer on Stackoverflow
Solution 4 - PhpMD. Shafayatul HaqueView Answer on Stackoverflow
Solution 5 - PhprdlowreyView Answer on Stackoverflow
Solution 6 - PhpKareemView Answer on Stackoverflow