PHP: How to check if variable is a “large integer”

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

Answer

So basically you want to check if a particular variable is integer-like?

function isInteger($var)
{
    if (is_int($var)) {
        // the most obvious test
        return true;
    } elseif (is_numeric($var)) {
        // cast to string first
        return ctype_digit((string)$var);
    }
    return false;
}

Note that using a floating point variable to keep large integers will lose precision and when big enough will turn into a fraction, e.g. 9.9999999999991E+36, which will obviously fail the above tests.

If the value exceeds INT_MAX on the given environment (32-bit or 64-bit), I would recommend using gmp instead and persist the numbers in a string format.

Leave a Reply

Your email address will not be published. Required fields are marked *