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

前端 未结 3 693
野趣味
野趣味 2020-11-28 12:41

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

相关标签:
3条回答
  • 2020-11-28 13:00

    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>";
    
    0 讨论(0)
  • 2020-11-28 13:11

    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.

    0 讨论(0)
  • 2020-11-28 13:17

    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;   
    }
    
    0 讨论(0)
提交回复
热议问题