CASE # 1:
I have the following code which outputs the correct number
<?php
$integer = 10000000000;
$array = array($integer);
print_r($array[0]); //output = 1000000000
?>
CASE # 2:
But when i explicitly type cast the same number to integer it gives different output
<?php
$integer = (int)10000000000;
$array = array($integer);
print_r($array[0]); //output = 1410065408
?>
CASE # 3:
If i make the number smaller by one 0 and type cast it, then it returns the correct number
<?php
$integer = (int)1000000000;
$array = array($integer);
print_r($array[0]); //output = 1000000000
?>
Why it is not producing the correct output in CASE # 2
?
You are overflowing the maximum size of an integer in your second example. In your first example, PHP automagically uses a larger numeric data type such as float
to hold the variable because it is too big for an int. When you explicitly cast it to an int
in example 2, because it is bigger than the max size it truncates it to that maximum size. In example 3 the number is short enough to contained in an int
. If you try casting it to a float
it will produce the correct result.
<?php
$integer = (float)10000000000;
$array = array($integer);
print_r($array[0]); //output = 10000000000
?>
The constant PHP_INT_SIZE
will tell you what the maximum supported int
size on your php installation is.
You are most likely exceeding max value of int on your platform.
From the Official PHP Doc:
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). Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
For 32-bit platforms:
Integers can be from -2147483648 to 2147483647
For 64-bit platforms:
Integers can be from -9223372036854775808 to 9223372036854775807
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With