2

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?

Community
  • 1
  • 1
Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • 1
    And do you have a computer with 200 terabytes of memory? – mario Jul 28 '13 at 19:11
  • Actually, I don't think it can have that many elements on a 32 bit system for lack of address space, even if the size field of the underlying C struct can hold that large a value. –  Jul 28 '13 at 19:12
  • 1
    @mario, that's not the point. – Pacerier Jul 28 '13 at 19:13
  • 1
    @mario Besides, how did you arrive at 200 TiB? That would be 51,2 KiB per element, which is a bit excessive for many kinds of records. –  Jul 28 '13 at 19:14

2 Answers2

7

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
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

This can never happen.

Unless this has changed in recent versions, 2^32 is the maximum number of elements in an array in PHP, even on 64 bit systems.

This is a limitation of the hashtable structure, which uses a uint for nTableSize and nNumOfElements: see PHP: do arrays have a maximum size?

Dewi Morgan
  • 1,143
  • 20
  • 31