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);
$result_str='';
foreach ($result as $value)
{
$result_str.=$valid_chars[$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:
$results=array();
for ($i=0; $i<=2000; $i++)
{
array_push($results, get_result());
}
$results=array_unique($results);
$cont=0;
$results_str='';
foreach ($results as $value)
{
$cont++;
$results_str.=$value.'
';
if ($cont>=1728)
{
break;
}
}
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:
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...
http://en.wikipedia.org/wiki/Infinite_monkey_theorem
thanks for sharing your information!
Publicar un comentario