如何生成唯一的6位数代码

par*_*pik 3 php string random

我想生成6位数的唯一代码但我希望前3个是字母表,最后3个是数字,如下例所示.

AAA111
ABD156
DFG589
ERF542...
Run Code Online (Sandbox Code Playgroud)

请帮助创建具有以上组合的代码..

下面是我的代码..

public function generateRandomString()  {
        $characters = '1234567890';
        $length = 6;
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
Run Code Online (Sandbox Code Playgroud)

Xor*_*lse 6

你想要前3个字符作为字母,最后3个字符作为数字?然后你应该彻底处理它们.

function genRandStr(){
  $a = $b = '';

  for($i = 0; $i < 3; $i++){
    $a .= chr(mt_rand(65, 90)); // see the ascii table why 65 to 90.    
    $b .= mt_rand(0, 9);
  }

  return $a . $b;
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用函数参数来添加动态性,对于随机顺序,您可以执行以下操作:

// PHP >= 7 code
function genRandStr(int $length = 6, string $prefix = '', string $suffix = ''){
  for($i = 0; $i < $length; $i++){
    $prefix .= random_int(0,1) ? chr(random_int(65, 90)) : random_int(0, 9);
  }

  return $prefix . $suffix;
}
Run Code Online (Sandbox Code Playgroud)

使用mt_rand()的PHP版本<7,否则random_int()建议.

您仍然需要检查可能的冲突并将其置于while循环中.