0

How to generate unique numeric value with fixed length from given data in PHP? For instance, I can have a string that contains numbers and characters and I need to generate unique numeric value with length 6. Thanks!

Igor Timoshenko
  • 1,001
  • 3
  • 14
  • 27
  • http://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php – Ghostman Nov 03 '12 at 19:22
  • Sooo... you're looking for a hash whose result is a 6 digit number (~16 bit), instead of the typical 32/64/128/... bit hex? – deceze Nov 03 '12 at 19:23
  • @deceze, yes and the result should be repeatable with small number of collisions. – Igor Timoshenko Nov 03 '12 at 19:27
  • What about picking one of the hashes from http://en.wikipedia.org/wiki/List_of_hash_functions with roughly 16bit results and doing a base conversion? – deceze Nov 03 '12 at 19:28

2 Answers2

2

You won't be able to generate a unique numeric value out of an input with any algorithm. That's the problem of converting an input into a pseudorandom output. If you have an input string of 20 characters and an output of only 6, there will be repeated results, because:

input of 20 characters (assuming 58 alphanumerical possibilities):

58^20 = 1.8559226468222606056912232424512e+35 possibilities

output of 6 characters (assuming 10 numerical possibilities):

10^6 = 1000000 possibilities

So, to sum up, you won't be able to generate a unique number out of a string. Your best chances are to use a hashing function like md5 or sha1. They are alphanumerical but you can always convert them into numbers. However, once you crop them to, let's say, 6 digits, their chances to be repeated increase a lot.

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93
0

It is impossible to generate a completely unique value given an arbitrary value with a limit on the number of characters unfortunately. There are an infinite number of possible values, while there are only 999999 possible values in a numeric value of length 6.

In PHP however you can do the following:

$list_of_numeric_values = array();

foreach ($list_of_given_values as $value)
{
     if (!in_array($value, $list_of_numeric_values))
         $list_of_numeric_values[] = $value;
}

After this is complete, the array then will have a unique key for each possible value you can use.

If you dont need to calculate these all at the same time you can follow a similar algorithm where instead of just "searching" the array using PHP perhaps its a SELECT on a MySQL table to see if the entry currently exists, and using the auto increment of the primary key to get your value.

Shane Fright
  • 385
  • 1
  • 9