PHP中数组的最大密钥大小是多少?

Ros*_*oss 65 php arrays key

我正在生成关联数组,键值是1..n列的字符串concat.

钥匙的最大长度会让我咬伤吗?如果是这样,我可能会停下来做不同的事情.

Gre*_*reg 79

它似乎仅受脚本内存限制的限制.

快速测试给我一个128mb的关键没问题:

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>";
Run Code Online (Sandbox Code Playgroud)

  • 哎呀!好吧,我当然不必担心我的键会略微超过255个字符. (11认同)
  • 请记住,PHP可能不是密钥大小的唯一限制因素.例如,如果它们太长,`memcache`可能会截断$ _SESSION中的键. (6认同)

Lus*_*sid 17

PHP中的字符串大小没有实际限制.根据手册:

注意:字符串变得非常大没有问题.PHP对字符串的大小没有限制; 唯一的限制是运行PHP的计算机的可用内存.

可以安全地假设这也适用于在数组中使用字符串作为键,但是根据PHP处理其查找的方式,当字符串变大时,您可能会注意到性能损失.


Bob*_*Bao 5

在zend_hash.h中,您可以找到zend_inline_hash_func()可以显示如何在PHP中散列键字符串的方法,因此使用小于8个字符的字符串长度的键对于性能更好.

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;   
}
Run Code Online (Sandbox Code Playgroud)