PHP Integer Precision
You might wonder how big an integer type can be in PHP, but the manual doesn’t specify the size of integer datatypes. Instead, there’s a brief fuzzy statement:
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that’s 32 bits signed). PHP does not support unsigned integers.
Well, we need to quantify that, so lets write some PHP code to find some big integers, and stop when we overflow:
for($i = 2; $i === (int) $i; $i = $i * 2){
echo "$i ";
}
This is a good start: it produces the following output:
2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824
I think we can do better with a binary search, though:
$max = 0;
$i = 1;
$step = 1;
while($max + 1 === (int) ($max + 1)){
if($i === (int) $i){
$max = max($i, $max);
$step += $step;
} else {
$i = $max;
$step = 1;
}
$i = $i + $step;
}
Looking for the largest non-overflowing php integer with this method returns:
2147483647
Since this is precisely 2^31 – 1, the upper bound of a standard signed 32bit integer, I am happy with php for now!
| This entry was posted on Monday, September 19th, 2005 at 1:23 pm and is tagged with unsigned integers, integer type, int max, binary search, max 1, max max, maximum value, upper bound, php code, step 1, overflow. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback. |

LOL pwned!
this value is also stored in PHP_INT_MAX
You never know till you try it!