PHP: How to check if variable is a "large integer"

Viewed 4003

I need to check if a parameter (either string or int or float) is a "large" integer. By "large integer" I mean that it doesn't have decimal places and can exceed PHP_INT_MAX. It's used as msec timestamp, internally represented as float.

ctype_digit comes to mind but enforces string type. is_int as secondary check is limited to PHP_INT_MAX range and is_numeric will accept floats with decimal places which is what I don't want.

Is it safe to rely on something like this or is there a better method:

if (is_numeric($val) && $val == floor($val)) {
    return (double) $val;
}
else ...
4 Answers

I did at the end of the function to check for numeric data.

return is_numeric($text)&&!(is_int(strpos($text,".",0)));

It will first check if it is numeric then check if there is no decimal in the string by checking if it found a position. If it did the returned position is an int so is_int() will catch it.

(strpos($text,".",0)==FALSE) would also work based on the strpos manual but sometimes the function seems to send nothing at all back like

echo (strpos($text,".",0));

could be nothing and the ==FALSE is needed.

Related