How to generate a set of unique random strings in PHP

I'm amazed in my daily work of how useful and easy to use is PHP.

Today I've to generate 1.728 random strings of 9 characters each.

Each string must contain only a subset of alphanumeric characters, no zero, no Ç, no Ñ, etc.

Of course there must no be repeated strings in the 1.728 results.

I've added the constraint, don't repeat the same character inside an string, to avoid, results like "AAAbbbCCC" for example.

Let's code:

function get_result()
$valid_chars=array("1", "2", "3", "4", "5", "6", "7", "8", "9"
, "a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
, "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

$result=array_rand($valid_chars, 9);
foreach ($result as $value)
return $result_str;

this easy function does the following, first declare the array of allowed chars in the resulting string $valid_chars, using array_rand we obtain 9 keys to the array randomly generated, for example $result could be {7, 10, 14, 20, 22, 30, 35, 42, 49}

Then we loop through the keys with a foreach and simply obtain the character associated to the key and concatenate to the $result_str string.

Finally the body of the php:


for ($i=0; $i<=2000; $i++)
array_push($results, get_result());


foreach ($results as $value)

if ($cont>=1728)
echo $results_str;

In this code we simply loop from 0 to 2000 calling the get_result() function and storing the result in an array.

Then we call the array_unique to avoid duplicated strings (for this reason we have generate a bit more than 1728 results) at this point $results have yet more than 1.728 valid and unique resulting strings.

Finally we loop through the array and break the loop when the limit of 1.728 strings are reached, adding to a resulting string each code, and then output the string.

Enjoy your new randomly generated codes !

2 comentarios:

Seize dijo...

How many sets of unique random string I have to generate to get the complete novel of "King Leard"?
It's like the monkey & the typewriter teorem...

dani dijo...

thanks for sharing your information!