生成一个预定义长度的随机数 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13169025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate a random number with pre-defined length PHP
提问by Karl
I'm trying to create a function using mt_rand() in order to generate a truly random number, since rand() just isn't suffice.
我正在尝试使用 mt_rand() 创建一个函数以生成一个真正的随机数,因为 rand() 是不够的。
The problem is I need to pre-define the length of the number, say I need a 10 digit random number.
问题是我需要预先定义数字的长度,比如说我需要一个 10 位的随机数。
Anyway, I've been messing around and this is what I've come up with:
无论如何,我一直在胡闹,这就是我想出的:
function randomNumber($length) {
$min = str_repeat(0, $length-1) . 1;
$max = str_repeat(9, $length);
return mt_rand($min, $max);
}
In theory that should work (as far as I can tell), but it doesn't. The length is completely random and it also throws out negative values.
理论上这应该有效(据我所知),但事实并非如此。长度是完全随机的,它也会抛出负值。
Any ideas?
有任何想法吗?
回答by Ry-
Unless you have one of those quantum-static thingies, you can't get a truly random number. On Unix-based OSes, however, /dev/urandomworks for "more randomness", if you really need that.
除非您拥有那些量子静态事物之一,否则您无法获得真正的随机数。然而,在基于 Unix 的操作系统上/dev/urandom,如果你真的需要的话,它可以实现“更多的随机性”。
Anyway, if you want an n-digit number, that's exactly what you should get: n individual digits.
无论如何,如果您想要一个 n 位数字,这正是您应该得到的:n 个单独的数字。
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
The reason your existing code isn't working is because 0000...01is still 1to mt_rand, and also that mt_rand's range isn't infinite. The negative numbers are integer overflows.
您现有的代码不起作用的原因0000...01是仍然1to mt_rand,而且它mt_rand的范围不是无限的。负数是整数溢出。
回答by Ray
Short and sweet:
简短而甜蜜:
I'm assuming only legitimate numbers, not strings like 00010. Try useing the size of your number to be:
我假设只有合法的数字,而不是像 00010 这样的字符串。尝试使用您的数字的大小:
$min = pow(10, $length - 1) ;
$max = pow(10, $length) - 1;
return mt_rand($min, $max);
The only one that doesn't work is when length is 1, a single digit number '0' won't be a possible value to be returned.
唯一不起作用的是当长度为 1 时,一位数字 '0' 将不会成为可能的返回值。
回答by Jazzer
Here is what I'm using:
这是我正在使用的:
function random_number($length)
{
return join('', array_map(function($value) { return $value == 1 ? mt_rand(1, 9) : mt_rand(0, 9); }, range(1, $length)));
}
One line, nice and simple! The number will never start with 0 and allows 0 at any other place.
一行,好看又简单!该数字永远不会以 0 开头,并且在任何其他地方都允许 0。
回答by King Leon
function randomNDigitNumber($digits)
{
$returnString = mt_rand(1, 9);
while (strlen($returnString) < $digits) {
$returnString .= mt_rand(0, 9);
}
return $returnString;
}
The first line ensures that no "0" precedes any number, for instance values like 012, 0598... will be discarded, the rest is easy
第一行确保没有“0”在任何数字之前,例如像 012、0598... 这样的值将被丢弃,其余的很容易
回答by user3183399
Use this for strings of a certain length with both letters and numbers. Tested.
将此用于具有字母和数字的特定长度的字符串。测试。
protected function randomToken($length = 4, $result='') {
for($i = 0; $i < $length; $i++) {
$case = mt_rand(0, 1);
switch($case){
case 0:
$data = mt_rand(0, 9);
break;
case 1:
$alpha = range('a','z');
$item = mt_rand(0, 25);
$data = strtoupper($alpha[$item]);
break;
}
$result .= $data;
}
return $result;
}
回答by user5513314
How about this:
这个怎么样:
function random($len)
{
static $track = [];
$min = 1 . str_repeat(0, $len - 1);
$max = str_repeat(9, $len);
$num = mt_rand($min, $max);
// was this number generated before?
if (in_array($num, $track))
{
// try again
return random($len);
}
return $track[] = $num;
}
Keeping track of generated numbers via static variable (which is initiated once) will prevent generating the same number twice, unless you go through the whole range, in which case you get stuck in infinite loop. For example:
通过静态变量(启动一次)跟踪生成的数字将防止生成相同的数字两次,除非您遍历整个范围,在这种情况下您会陷入无限循环。例如:
for ($i = 0; $i < 10; $i++)
{
random(1);
}
回答by Swapnil Ghone
just sepcify the range to rand method , if you need 4 digit random number then just use it as
只需将范围指定为 rand 方法,如果您需要 4 位随机数,则只需将其用作
rand(1000,9999);
回答by Michael
function randomNumber($length) {
$min = 1 . str_repeat(0, $length-1);
$max = str_repeat(9, $length);
return mt_rand($min, $max);
}
you have your concat 1 in the wrong spot, your range is this for $length=2: {01,99} - sometimes its 01-09, that is represented as 1-9 not 01-09. Just start from 10: {10,99} will be your range.
您将 concat 1 放在错误的位置,您的范围是 $length=2: {01,99} - 有时是 01-09,表示为 1-9 而不是 01-09。从 10 开始:{10,99} 将是您的范围。
回答by mario
You shouldn't start with the length constraining the random numbers. Rather accumulate a long enough output, then cut it to the right length:
你不应该从限制随机数的长度开始。而是积累足够长的输出,然后将其切成合适的长度:
while (strlen($value) < $length) {
$value .= str_pad(mt_rand(00000, 99999), 5, "0", STR_PAD_LEFT);
}
// as pairs of five were added before, eventually remove some again
return substr($value, 0, $length);
The padding should be there, because even zeros are randomly generated and should be retained.
填充应该在那里,因为即使是零也是随机生成的,应该保留。

