Hashing an entire PHP array into a unique value

49,462

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...

Share:
49,462
loneboat
Author by

loneboat

Updated on July 11, 2022

Comments

  • loneboat
    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
    loneboat over 13 years
    Thanks for the answer. Any reason serialize would be any better?
  • Fieg
    Fieg about 11 years
    Would love to see some benchmarks for this method and it's alternatives.
  • Gogowitsch
    Gogowitsch over 8 years
    @fieg: apparently serialize wins performance-wise. Here's the data: stackoverflow.com/a/32846231/680382
  • Agi
    Agi over 8 years
    As pointed out on link metioned by @gogowitsch, you will need to also account for the ordering of the array.
  • Amir Iskander
    Amir Iskander over 5 years
    Using 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
    mehov about 5 years
    I 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
    Guilherme Sampaio about 3 years
    This is the best one. I have extracted the necessary fields from the array to hash it better.