tags:

views:

411

answers:

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?

A: 

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.

masfenix
+9  A: 

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().

yjerem
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
A: 

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.

PEZ
A: 

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 :)

navitronic
Rob
+1  A: 

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

null