Why does php array integer key get negative (<0)?

var_dump(array_filter(array(4294967295 => 22)));

      

Result:

array(1) {  
    [-1] =>  
    int(22)
}

      

Why is the key <0?

+3


source share


2 answers


The maximum size is int

as follows: -

PHP 32-bit builds:

Integers can be from -2147483648 to 2147483647

      



64-bit PHP builds:

Integers can be from -9223372036854775808 to 9223372036854775807

      

You seem to be using 32 bit assemblies and why you are getting this problem.

+6


source


This is due to arithmetic overflow . Since the largest integer number in PHP is PHP_INT_MAX

, it is only 2147483647

(32-bit).

Thus, the "so-called" number 2147483648

will be overflowing, then it will come -2147483648

, 2147483649

become, -2147483647

and so on ...

Your number 4294967295

finally ends with -1.



All of this is because in computer science we use Two Complement to display less than 0 numbers. It doesn't make sense in real life, but for a computer, Two's Complement is much easier and faster to compute.

For your problem, you can change your PHP to 64 bit. Or get around it by not using the number, which in this case is> PHP_INT_MAX.

+6


source







All Articles