I want to generate a random string of about 5 characters long. I can create it ok, but I'm having trouble checking if it exists in an array (or database in real situation) and creating a new one if it does.
I use a function like this to generate the string:
function rand_string(){
return substr(md5(microtime()), 0, 5);
}
But them I'm lost.
Try this:
function rand_string(){
$str = substr(md5(microtime()), 0, 5);
if(exists_in_db($str)) $str = rand_string();
return $str;
}
Just a warning that if you are using this to generate a unique string by adding it to the database once you've determined it's not been used then this is not safe in a concurrent environment.
In the interval between you checking it's not in the database, and adding a record containing it later on another thread could do the same...
If you are using it this way, probably the safest approach is to ensure that the field containing the string has a unique constraint on it and try to add it. If you suceeded in adding it then you know it was unique, if you didn't then it wasn't. And this is safe to do in a multithreaded environment.
If you are simply checking against a static list of strings and do not intend to add the generated string to the database then ignore this post :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With