Question

On a 32-bit system, an array can have as much as 4294967295 elements (as per Artefacto's post on another thread).

However, count returns the number of elements as an int, and on a 32-bit system, an int is at most 2147483647.

What will count return when an array has more than 2147483647 elements?

Était-ce utile?

La solution

First of all, based on the size of an array element, you would need at least 163 GiB (32-bit) or 309 GiB (64-bit) of memory before you can observe this behaviour.

The return value of count() is based on zend_hash_num_elements():

ZEND_API int zend_hash_num_elements(const HashTable *ht)

This return value then gets cast into a long before it's returned to your code; this causes count() to return a seemingly negative value. This can be fixed by forcing it back into an unsigned value:

$c = count($array_with_pow_2_32_elements);
echo $c; // -2147483648
printf("%u\n", $c); // 2147483648

Or:

$c = sprintf('%u', $c);
echo $c; // 2147483648
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top