如何生成6位数的唯一数字?

AAA*_*AAA 29 php random

如何生成6位数的唯一数字?我有适当的验证机制来检查重复的条目.

Cha*_*les 116

$six_digit_random_number = mt_rand(100000, 999999);
Run Code Online (Sandbox Code Playgroud)

当然,100,000到999,999之间的所有数字都是六位数.

  • 你知道从这种方法生成的随机数是多少吗?如果获得相同的随机数怎么办? (2认同)

Tim*_*per 33

如果你想要它开始000001并去999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));
Run Code Online (Sandbox Code Playgroud)

请注意,它存储为字符串.


Mav*_*287 11

有一些很好的答案,但许多使用被标记为不加密安全的函数。如果您想要一个加密安全的随机 6 位数字,您可以使用如下内容:

\n
$key = random_int(0, 999999);\n$key = str_pad($key, 6, 0, STR_PAD_LEFT);\nreturn $key;\n
Run Code Online (Sandbox Code Playgroud)\n

这还包括 000182 等数字以及其他示例中排除的其他数字。

\n

您还可以使用循环使每个数字随机并生成具有所需数量的随机数:

\n
function generateKey($keyLength) {\n    // Set a blank variable to store the key in\n    $key = "";\n    for ($x = 1; $x <= $keyLength; $x++) {\n        // Set each digit\n        $key .= random_int(0, 9);\n    }\n    return $key;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

作为参考, random_int \xe2\x80\x94 生成加密安全的伪随机整数,适合在无偏结果至关重要的情况下使用,例如在扑克游戏中洗牌时。” - php.net/random_int

\n


Fro*_*y Z 10

另一个:

str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
Run Code Online (Sandbox Code Playgroud)

无论如何,为了保持唯一性,您必须检查您的号码是否尚未使用过.

您告诉您检查重复项,但要小心,因为当使用大多数数字时,获取新数字的"尝试次数"(以及因此花费的时间)将增加,可能导致非常长的延迟并浪费CPU资源.

我会建议,如果可能的话,跟踪可用的ID的数组,然后随机选择一个ID 可用的人当中,做这样的事情(如果ID列表保存在内存中):

$arrayOfAvailableIDs = array_map(function($nb) {
    return str_pad($nb, 6, '0', STR_PAD_LEFT);
}, range(0, 999999));

$nbAvailableIDs = count($arrayOfAvailableIDs);

// pick a random ID

$newID = array_splice($arrayOfAvailableIDs, mt_rand(0, $nbAvailableIDs-1), 1);
$nbAvailableIDs--;
Run Code Online (Sandbox Code Playgroud)

即使ID列表存储在数据库中,您也可以执行类似的操作.


vir*_*rus 8

<?php
$file = 'count.txt';

//get the number from the file
$uniq = file_get_contents($file);

//add +1
$id = $uniq + 1 ;

// add that new value to text file again for next use
file_put_contents($file, $id);

// your unique id ready
echo $id;
?>
Run Code Online (Sandbox Code Playgroud)

我希望这会很好.我在我的网站上使用相同的技术.


小智 7

这是另一个:

substr(number_format(time() * rand(),0,'',''),0,6);
Run Code Online (Sandbox Code Playgroud)


小智 5

$characters = '123456789';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 6; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}
$pin=$randomString; 
Run Code Online (Sandbox Code Playgroud)


Yes*_*rry 5

在 PHP 7.0+ 中,我建议random_int($min, $max) 超过 mt_rand().

$randomSixDigitInt = \random_int(100000, 999999);
Run Code Online (Sandbox Code Playgroud)

来自 php.net:

注意 此函数不会生成加密安全值,不应用于加密目的。如果您需要加密安全值,请考虑改用 random_int()、random_bytes() 或 openssl_random_pseudo_bytes()。

所以这主要取决于上下文。我还要补充一点,从 PHP 7.1.0 开始rand(),现在是mt_rand().

干杯