Question

I am looking for a function that would look like

$hash = someFunction($value1,$value2);

The hash would be unique based on the values, HOWEVER, it should return the same hash regardless of the order of the parameters. So (3,5) would return the same hash as (5,3).

Is there such a known algorithm?

To give context on what I am trying to achieve, in my database I have a table representing a message between user1 and user2, with a pair of columns user1,user2. I want to GROUP BY pairs, regardless of the order. Meaning, I want to see full conversations between 2 users.

I'm thinking if I could add to the table a string identifying a unique pair, it would make my life easier.

Était-ce utile?

La solution

How about sorting $value1 and $value2 first, concatenating them, and then using any known hash algorithm?

Autres conseils

Well, I would do it like this (Assuming the both params are of same data type)

function someFunc($val1, $val2){
  if($val1>$val2){
    $val3 = $val2;
    $val2 = $val1;
    $val1 = $val3;
  }
  //if the params are string, compare the length of string and assign $val1 with the greater length, and $val2 with smaller
  //if the length of strings are equal, compare the string and assign $val1 with the string that comes ahead alphabetically,
  //if both strings are identical, you can not-care about the order of params.

//Do whatever you would like to do
}

Now even if you call the function like

someFunc(5,3)

the value of params are swapped automatically making the call identical to

someFunc(3,5)

Similarly the same thing applies for strings

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top