Problem with integer type

CASE # 1: I have the following code that outputs the correct number

 <?php $integer = 10000000000; $array = array($integer); print_r($array[0]); //output = 1000000000 ?> 

CASE # 2: But when I explicitly type one integer into an integer, it gives a different output

 <?php $integer = (int)10000000000; $array = array($integer); print_r($array[0]); //output = 1410065408 ?> 

CASE # 3: If I make the number less by one 0 and type it, it will return the correct number

 <?php $integer = (int)1000000000; $array = array($integer); print_r($array[0]); //output = 1000000000 ?> 

Why doesn't it produce the correct output in CASE # 2 ?

+7
arrays php
source share
3 answers

Most likely, you will exceed the maximum int value on your platform.

From the Official PHP Doc :

The size of the integer depends on the platform, although the maximum value of about two billion is the usual value (32 bits signed). Integer size can be determined using the constant PHP_INT_SIZE and the maximum value using the constant PHP_INT_MAX with 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

+4
source share

In your second example, you are overflowing the maximum size of an integer. In your first example, PHP automatically uses a larger numeric data type, such as float , to hold a variable because it is too large for an int. When you explicitly apply it to an int in Example 2, since it is larger than the maximum size, it trims it to that maximum size. In Example 3, the number is short enough to be contained in an int . If you try to apply it to a float , this will lead to the correct result.

 <?php $integer = (float)10000000000; $array = array($integer); print_r($array[0]); //output = 10000000000 ?> 

The PHP_INT_SIZE will tell you what is the maximum supported int size for your php installation.

+1
source share

The maximum value of an integer depends on the platform, but it is about 2 billion. CASE No. 2 is 10 billion.

If you want typecast to use float, it has a much higher limit ...

Link: http://php.net/manual/en/language.types.integer.php

0
source share

All Articles