3 ms·
is_numeric doesn't help you if you want to find out whether the value in $foobar is a string that represents an integer or not. The only way to safely do that
by pilif 16y ago
is_numeric doesn't help you if you want to find out whether the value in $foobar is a string that represents an integer or not.
The only way to safely do that in PHP is, sadly, a regular expression.
is_int checks the type, so is_int('1234') is as false as is_int('123n') or is_int('abc')
is_numeric is too permissive as it allows floating point numbers or even hexadecimal values.
intval($foobar) == $foobar doesn't work due to intval('123n') == 123
intval($foobar) === $foobar naturally doesn't work because the types don't match.
The code in question is the receiving end of some machine generated communication that is supposed to closely follow a specification.
During validation if the spec says that it requires a base10 integer encoded in ASCII, then 0xFF isn't permissible just because is_numeric() says so.
- wvenable 16y agoI have this function in my own code. You can adjust it's permissiveness your taste: function is_intval($value) { if (is_integer($value)) return true; if (is_bool($value)) return true; if (!is_numeric($value)) return false; if (is_float($value) && floatval(intval($value)) == $value) return true; if (is_string($value) && strval(intval($value)) == $value) return true; return false; }
- pilif 16y ago... hereby proving my point that PHP's default conversions are a bit... strange.
- wvenable 16y agoI never said it wasn't weird!! I just said that it's not really a practical problem in most cases. Perhaps you do have to be extra careful and I'm just so used to it that I don't give it a second thought.