Matthew Sims wrote:
I recently purchased George Schlossnagle's Advanced PHP Programming and on page 85 in the Error Handling chapter, he made a reference about the is_int function.
In the above function example he had: if (!preg_match('/^\d+$/',$n) || $n < 0) {....
In which he mentions: It might be strange to choose to evaluate whether $n is an integer by using a regular expression instead of the is_int function. The is_int function, however, does not do what you want. It only evaluates whether $n has been typed as a string or as an integer, not whether the value of $n is an integer.
Can anyone comment on this?
Sure. He's right, but this shouldn't be a surprise, since it's documented as such:
Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
(From http://www.php.net/is_int)
In my opinion, using the regex engine for this is overkill. Another way is to do something like this (from the old days before is_numeric()):
if ((string) (int) $int == $int) { echo "'$int' is an integer.\n"; } else { echo "'$int' is not an integer.\n"; }
Now, this won't work for hex integers inside strings, but then, neither will the above regex. Also, for some reason the test you posted fails for negative values, which the simpler typecast test does not do. (There is a user note on the is_numeric() manual page with a function using the casting method for a wider range of numeric values, if you want it.)
Mostly, though, is_numeric() will work just fine, but doesn't discriminate against floats etc (which both snippets above do).
Torben
--Matthew Sims --<http://killermookie.org>
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php