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

PhpArraysKey

Php Problem Overview


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.

Php Solutions


Solution 1 - 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>";

Solution 2 - Php

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.

Solution 3 - Php

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;   
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRossView Question on Stackoverflow
Solution 1 - PhpGregView Answer on Stackoverflow
Solution 2 - PhpLusidView Answer on Stackoverflow
Solution 3 - PhpBob BaoView Answer on Stackoverflow