PHP best way to MD5 multi-dimensional array?

后端 未结 13 2067
别那么骄傲
别那么骄傲 2020-12-07 11:48

What is the best way to generate an MD5 (or any other hash) of a multi-dimensional array?

I could easily write a loop which would traverse through each level of the

13条回答
  •  醉话见心
    2020-12-07 12:25

    Answer is highly depends on data types of array values. For big strings use:

    md5(serialize($array));
    

    For short strings and integers use:

    md5(json_encode($array));
    

    4 built-in PHP functions can transform array to string: serialize(), json_encode(), var_export(), print_r().

    Notice: json_encode() function slows down while processing associative arrays with strings as values. In this case consider to use serialize() function.

    Test results for multi-dimensional array with md5-hashes (32 char) in keys and values:

    Test name       Repeats         Result          Performance     
    serialize       10000           0.761195 sec    +0.00%
    print_r         10000           1.669689 sec    -119.35%
    json_encode     10000           1.712214 sec    -124.94%
    var_export      10000           1.735023 sec    -127.93%
    

    Test result for numeric multi-dimensional array:

    Test name       Repeats         Result          Performance     
    json_encode     10000           1.040612 sec    +0.00%
    var_export      10000           1.753170 sec    -68.47%
    serialize       10000           1.947791 sec    -87.18%
    print_r         10000           9.084989 sec    -773.04%
    

    Associative array test source. Numeric array test source.

提交回复
热议问题