What is the max key size for an array in PHP?

It seems to be limited only by the script's memory limit.

A quick test got me a key of 128mb no problem:

ini_set('memory_limit', '1024M');

$key = str_repeat('x', 1024 * 1024 * 128);

$foo = array($key => $key);

echo strlen(key($foo)) . "<br>";
echo strlen($foo[$key]) . "<br>";

There is no practical limit to string size in PHP. According to the manual:

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

It is safe to assume that this would apply to using strings as keys in arrays as well, but depending on how PHP handles its lookups, you may notice a performance hit as strings get larger.


In zend_hash.h, you can find zend_inline_hash_func() method that can show how to hash key string in PHP, So use key which string length less than 8 characters is better for performance.

static inline ulong zend_inline_hash_func(char *arKey, uint nKeyLength) {

register ulong hash = 5381;

/* variant with the hash unrolled eight times */
for (; nKeyLength >= 8; nKeyLength -= 8) {
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
    hash = ((hash << 5) + hash) + *arKey++;
}
switch (nKeyLength) {
    case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 5: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 2: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
    case 1: hash = ((hash << 5) + hash) + *arKey++; break;
    case 0: break;  EMPTY_SWITCH_DEFAULT_CASE()
}
    return hash;   
}