Hashing an entire PHP array into a unique value

PhpArraysHash

Php Problem Overview


Looking for a way to produce a filename-safe hash of a given PHP array. I'm currently doing:

$filename = md5(print_r($someArray, true));

... but it feels "hacky" using print_r() to generate a string unique to each array.

Any bright ideas for a cleaner way to do this?

EDIT Well, seems everyone thinks serialize is better suited to the task. Any reason why? I'm not worried about ever retrieving information about the variable after it's hashed (which is good, since it's a one-way hash!). Thanks for the replies!

Php Solutions


Solution 1 - Php

Use md5(serialize()) instead of print_r().

print_r()'s purpose is primarily as a debugging function and is formatted for plain text display, whereas serialize() encodes an array or object representation as a compact text string for persistance in database or session storage (or any other persistance mechanism).

Solution 2 - Php

Alternatively you could use json_encode

Solution 3 - Php

serialize() should work fine.

It has the additional advantage of invoking the __sleep magic method on objects, and being the cleanest serialization method available in PHP overall.

Solution 4 - Php

What about serialize?

$filename = md5(serialize($someArray));

Solution 5 - Php

Using serialize() might be more conservative if you want to keep the type, etc...

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
QuestionloneboatView Question on Stackoverflow
Solution 1 - PhpMichael BerkowskiView Answer on Stackoverflow
Solution 2 - PhpgeneralhenryView Answer on Stackoverflow
Solution 3 - PhpPekkaView Answer on Stackoverflow
Solution 4 - PhpDampView Answer on Stackoverflow
Solution 5 - Phpgreg0ireView Answer on Stackoverflow