30

Is there a limit for an array in PHP?

hakre
  • 193,403
  • 52
  • 435
  • 836
Febin Joy
  • 309
  • 1
  • 3
  • 4

2 Answers2

46

Yes, there's a limit on the maximum number of elements. The hash table structure (arrays are basically wrappers around a hash table) is defined like this (PHP 5.3):

typedef struct _hashtable {
    uint nTableSize;
    uint nTableMask;
    uint nNumOfElements;
    ulong nNextFreeElement;
    Bucket *pInternalPointer;   /* Used for element traversal */
    Bucket *pListHead;
    Bucket *pListTail;
    Bucket **arBuckets;
    dtor_func_t pDestructor;
    zend_bool persistent;
    unsigned char nApplyCount;
    zend_bool bApplyProtection;
#if ZEND_DEBUG
    int inconsistent;
#endif
} HashTable;

given that

typedef unsigned int uint;

the limit is the maximum size of an unsigned int (typically 2^32-1 on a 32-bit OS and on most 64-bit OS).

In practice, however, except on machines with lots of RAM and 32-bit ints, you will always hit the memory limit before this becomes an issue.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • You'll probably find you run into serious performance problems populating and dereferencing array elements before you hit the memory limit on most systems. – symcbean Jun 14 '10 at 13:21
  • @symcbean I doubt it. Lookups and additions take an average constant time. The only thing that can take time is resizing the hash table, but that be avoided if the total number of items can be known in advance. – Artefacto Jun 14 '10 at 13:41
  • 1
    @Artefacto, why do you say *most* 64-bit OS has only 2^32-1 for unsigned int? – Pacerier Jul 28 '13 at 19:04
  • 2
    @Pacerier Google for "ILP64". – Artefacto Jul 28 '13 at 20:26
  • Since PHP 7.0, a check in range() limits the array size to 2^(32-1)-1. [via a related Q&A](https://stackoverflow.com/a/73885850/367456). – hakre Aug 03 '23 at 12:15
8

The only thing I've come across in reference to php is this from bytes.com/forum:

I don't think there is a limit on how big an array can be, but there is a limit on how much memory your script can use.

The 'memory_limit' directive in the php.ini configuration file holds the max amount of memory your scripts can consume. Try changing this, see if that helps.

Community
  • 1
  • 1
ChrisF
  • 134,786
  • 31
  • 255
  • 325