Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the integer key of a php array become negative (< 0)?

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

The result:

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

Why the key is < 0 ?

like image 520
tanteng Avatar asked Mar 05 '26 06:03

tanteng


2 Answers

Max size of intare as follows:-

32-bit builds of PHP:

Integers can be from -2147483648 to 2147483647

64-bit builds of PHP:

Integers can be from -9223372036854775808 to 9223372036854775807

It seems you are using 32 bit builds and that's why you are getting that problem.

like image 131
Anant Kumar Singh Avatar answered Mar 06 '26 19:03

Anant Kumar Singh


This is because of Arithmetic overflow. Since biggest integer number in PHP is PHP_INT_MAX, which is only 2147483647 (32-bit).

So the "so-called" number 2147483648 is overflowed then will come -2147483648, 2147483649 becomes -2147483647 and so on...

Your number 4294967295 finally ends up at -1.

This whole things happens because in computer science, we use Two's Complement to represents smaller than 0 numbers. This does not make sense in real life, but for computer, Two's complement is much more easier and faster to compute.

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

like image 29
Envil Avatar answered Mar 06 '26 20:03

Envil