74

I am generating associative arrays and the key value is a string concat of 1..n columns.

Is there a max length for keys that will come back to bite me? If so, I'll probably stop and do it differently.

Ross
  • 743
  • 1
  • 5
  • 4
  • 2
    Nice illustration RoBorg, if I have a key over 128mb I'll probably find myself on the daily WTF. Many thanks. – Ross Jan 22 '09 at 13:18

3 Answers3

93

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>";
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 12
    yikes! well I certainly don't have to worry about my keys going slightly over 255 chars then. – thomasrutter May 05 '09 at 04:51
  • 7
    Keep in mind that PHP may not be the only limiting factor on key size. For example, `memcache` may truncate keys from $_SESSION if they are too long. – jchook Sep 30 '16 at 20:39
17

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.

Lusid
  • 4,518
  • 1
  • 24
  • 24
7

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;   
}
Bob Bao
  • 129
  • 1
  • 4