Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce a unique string from a php array

Tags:

arrays

php

hash

I need a unique string from an array so that I can tell when it changes without measuring the inputs of that array. I'm trying to work out if it is computationally efficient to calculate a value rather than add code to look out for changes in the array. The array itself can have a variety of values and for future proofing I don't want to try and measure whether new values have been added to the array, I'd much rather just create some string or hash that will change if the array itself changes.

So for example:

$a = Array(
'var1' => 1,
'var2' => 2,
'var3' => 3,
);

If I was to use md5(http_build_query($a)) perhaps with an added ksort to confirm that the order of the keys haven't changed this might then produce a unique string that I can use to compare against another run of the application to evaluate whether the array has changed.

I'm looking for an alternate, possibly faster or more elegant solutions to this.

like image 675
Jason Avatar asked Feb 25 '11 00:02

Jason


People also ask

How do you make an array of objects unique in PHP?

array_unique works by casting the elements to a string and doing a comparison. Unless your objects uniquely cast to strings, then they won't work with array_unique. Instead, implement a stateful comparison function for your objects and use array_filter to throw out things the function has already seen.

How do you make an array unique?

A simple solution to make each duplicate value unique is to keep incrementing it repeatedly until it is not unique.

Is unique in array PHP?

The array_unique() is a built-in function in PHP and this function removes duplicate values from an array. If there are multiple elements in the array with same values then the first appearing element will be kept and all other occurrences of this element will be removed from the array.

How can I get unique values from two arrays in PHP?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.


1 Answers

Im use md5(serialize($array)) for this. Its better, because works for multi-dimensional arrays.

like image 140
delphist Avatar answered Sep 18 '22 20:09

delphist