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);
}
Run Code Online (Sandbox Code Playgroud)
But them I'm lost.
试试这个:
function rand_string(){
$str = substr(md5(microtime()), 0, 5);
if(exists_in_db($str)) $str = rand_string();
return $str;
}
Run Code Online (Sandbox Code Playgroud)
只是一个警告,如果您使用它来生成一个唯一的字符串,一旦您确定它未被使用就将其添加到数据库中,那么这在并发环境中是不安全的。
在检查它不在数据库中的间隔内,稍后在另一个线程上添加包含它的记录可以做同样的事情......
如果您以这种方式使用它,可能最安全的方法是确保包含字符串的字段对其具有唯一约束并尝试添加它。如果您成功添加了它,那么您就知道它是独一无二的,如果您没有添加,那么它就不是。这在多线程环境中是安全的。
如果您只是检查静态字符串列表并且不打算将生成的字符串添加到数据库中,请忽略此帖子:P
| 归档时间: |
|
| 查看次数: |
2325 次 |
| 最近记录: |