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

medusa1414 picture medusa1414 · Jul 10, 2012 · Viewed 133k times · Source

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

Answer

user1479055 picture user1479055 · Jul 10, 2012

ctype_digit was built precisely for this purpose.