Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing an entire PHP array into a unique value [duplicate]

Tags:

arrays

php

hash

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!

like image 312
loneboat Avatar asked Feb 23 '11 21:02

loneboat


People also ask

Is PHP hash unique?

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

How do you get unique values in a multidimensional array?

A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.

How are duplicates removed from an array without using any library PHP?

An array is defined and duplicate elements from the array can be found and removed using the 'array_flip' function, that basically reverses the keys/index as values and values as keys.

What is Array_unique?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


1 Answers

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

like image 114
Michael Berkowski Avatar answered Sep 19 '22 13:09

Michael Berkowski