Search code examples
php32-bit

PHP intval() changes number NOT 2147483647


I'm running PHP 5.3.13 and when I execute

php -r "echo intval(9999999999);"

It outputs 1410065407.

When I execute

php -r "echo intval(PHP_INT_MAX);"

It outputs 2147483647.

The smaller integer is causing my code some issues. Why the difference?


Solution

  • In your case, the value 9999999999 is being stored as a float. You can verify this with var_dump(9999999999). When it's casted to a signed integer, the value is truncated to 32 bits which gives the value 1410065407.

    You can verify this calculation by hand or by using the GMP math extension:

    $num = gmp_init("9999999999");
    $bits = gmp_pow(2, 32);
    
    var_dump(gmp_strval(gmp_mod($num, $bits)));
    // string(10) "1410065407"