PHP best way to MD5 multi-dimensional array?

Viewed 69613

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 array, concatenating each value into a string, and simply performing the MD5 on the string.

However, this seems cumbersome at best and I wondered if there was a funky function which would take a multi-dimensional array, and hash it.

14 Answers

Aside from Brock's excellent answer (+1), any decent hashing library allows you to update the hash in increments, so you should be able to update with each string sequentially, instead having to build up one giant string.

See: hash_update

Note that serialize and json_encode act differently when it comes to numeric arrays where the keys don't start at 0, or associative arrays. json_encode will store such arrays as an Object, so json_decode returns an Object, where unserialize will return an array with exact the same keys.

I didn't see the solution so easily above so I wanted to contribute a simpler answer. For me, I was getting the same key until I used ksort (key sort):

Sorted first with Ksort, then performed sha1 on a json_encode:

ksort($array)
$hash = sha1(json_encode($array) //be mindful of UTF8

example:

$arr1 = array( 'dealer' => '100', 'direction' => 'ASC', 'dist' => '500', 'limit' => '1', 'zip' => '10601');
ksort($arr1);

$arr2 = array( 'direction' => 'ASC', 'limit' => '1', 'zip' => '10601', 'dealer' => '100', 'dist' => '5000');
ksort($arr2);

var_dump(sha1(json_encode($arr1)));
var_dump(sha1(json_encode($arr2)));

Output of altered arrays and hashes:

string(40) "502c2cbfbe62e47eb0fe96306ecb2e6c7e6d014c"
string(40) "b3319c58edadab3513832ceeb5d68bfce2fb3983"

in some case maybe it's better to use http_build_query to convert array to string :

md5( http_build_query( $array ) );
Related