Hashing an entire PHP array into a unique value
Solution 1
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
Alternatively you could use json_encode
Solution 3
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
What about serialize?
$filename = md5(serialize($someArray));
Solution 5
Using serialize()
might be more conservative if you want to keep the type, etc...
![loneboat](https://i.stack.imgur.com/vKF6B.png?s=256&g=1)
loneboat
Updated on July 11, 2022Comments
-
loneboat almost 2 years
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!
-
loneboat over 13 yearsThanks for the answer. Any reason serialize would be any better?
-
Fieg about 11 yearsWould love to see some benchmarks for this method and it's alternatives.
-
Gogowitsch over 8 years@fieg: apparently serialize wins performance-wise. Here's the data: stackoverflow.com/a/32846231/680382
-
Agi over 8 yearsAs pointed out on link metioned by @gogowitsch, you will need to also account for the ordering of the array.
-
Amir Iskander over 5 yearsUsing json_encode to provide a hashing seed is not safe. For example, if the array you are using with json_encode has a non UTF-8 character, json_encode will return false, this will make all your md5 hashes the same.
-
mehov about 5 yearsI love how this is the first answer posted, and yet gotten right from the first go, without even one edit over all these years
-
Guilherme Sampaio about 3 yearsThis is the best one. I have extracted the necessary fields from the array to hash it better.