5

I read on a forum that you can't completely trust is_numeric(). It lets through "0xFF" for example which is an allowed hexadecimal...

So my question is can you trick is_numeric? Will I need to use a regex to do it correctly?

5 Answers 5

12

Here is what is_numeric() considers to be a numeric string:

Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

If you only want to check if a string consists of decimal digits 0-9, you could use ctype_digit().

1
  • It's kind of comical that VB.NET devs were scolded for using ctypes because .NET allowed for proper data type checking but in PHP it's the preferred way.
    – TravisO
    Jan 13, 2009 at 20:16
2

One can also check using ctype_digit() to check if its a true number.

0

Regex would obviously be your better option, however it does come with an overhead. So it really depends on your situation and what you want to do.

0

Is it for validating user input? Then the overhead of using a regexp or asserting it doesn't contain an "x" and is_numeric() wouldn't be too much overhead.

0

If you just want to check that something is an integer, try this:

function isInteger($value){
    return (is_numeric($value) ? intval($value) == $value : false);
}

If you want to check for floats too then this won't work obviously :)

1
  • 1
    Why not simply return is_numeric( $value ) && intval( $value ) == $value? Easier to read.
    – Rob
    Jan 13, 2009 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.