我正在为脚本创建一个随机的5个字符的引脚。我想知道是否有其他人有更好的?
$pin = '';
while($i != 5){
$string = '23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ';
$pos = rand(0,(strlen($string)-1));
$pin = $pin . $string[$pos];
$i++;
}
echo $pin;
答案 0 :(得分:3)
略有不同/更短。没有理由每次都声明有效字符,并且for循环通常被认为是优于while。
$pinlength = 5;
$charSet = '23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ';
$pin = '';
for($a = 0; $a < $pinlength; $a++) $pin .= $charSet[rand(0, strlen($charSet))];
echo $pin;
或者,只是为了它的地狱:
$makeCharacterSelect =
function ($charSet) {return function use ($charSet)
{return $charSet[rand(0, strlen($charSet))];};
$pinlength = 5; $c = $makeCharacterSelect('23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ');
$pin = '';
for($a = 0; $a < $pinlength; $a++) $pin .= $c();
答案 1 :(得分:2)
$pin = substr(uniqid(), 0, 5); // Mind you, this doesn't contain
// upper-case letters