简体   繁体   English

如何生成x位随机数?

[英]How to generate x digit random number?

I have to generate 16 digit random number something like recharg card pin number.(including 0 at starting place) This is my code 我必须生成16位随机数,例如充值卡密码。(在起始位置包括0)这是我的代码

function gen_num($len) {
    $rand   = '';
    while(!(isset($rand[$len-1]))){
        $rand   .= mt_rand(0,9);
    }
    return substr( $rand , 0 , $len );
}

It works fine but takes time to generate.if i want to generate 1000 pin at a same time like 它工作正常,但需要花费一些时间来生成。如果我想同时生成1000引脚

foreach($i=0;$i<=1000;$i++){
 get_num(16)
}

It takes more time.What is the best way to generate this kind of pin? 这需要更多时间。生成这种引脚的最佳方法是什么?

you may try this function.this will work fine. 您可以尝试使用此功能。

function getRandomNumber($len = "15")
{
    $better_token = $code=sprintf("%0".$len."d", mt_rand(1, str_pad("", $len,"9")));
    return $better_token;
}

for($i=0;$i<=1000;$i++){
    $codes[]=getRandomNumber(16);
}

in $code array you will get all 16 digit number with including 0.Output will be generated like below 在$ code数组中,您将获得所有16位数字,包括0.将生成如下所示的输出

Array
(
    [0] => 6432618102990092
    [1] => 5412363498471678
    [2] => 8415870470926167
    [3] => 2724858690053225
    [4] => 3719462379813195
    [5] => 0322053456788270
    [6] => 5085590323433281
    [7] => 3586620986461640
    [8] => 5041978429071606
    [9] => 0722051602788270
.....
$a = '';
      for ($i = 0; $i<16; $i++) 
    {
        $a .= mt_rand(0,9);
    }

you can use this function for generate random number. 您可以使用此功能生成随机数。

it's possible to same number generate twise so you can put this number in array and check in array number is already there or not. 可能会有相同的数字生成twise,因此您可以将此数字放入数组中,并检查数组号是否已存在。

    function gen_num() {
        $rand   = 0;
        for ($i = 0; $i<15; $i++) 
            {
                $rand .= mt_rand(0,9);
            }
        return $rand;
    }



foreach($i=0;$i<=1000;$i++){
 echo get_num();
}

o/p O / P

1992282192849338
2539119565182977
8186185479424499
9762937534145386
5565837949946845
6487684896937977
1437518184397774
1586381543857153
5673128433587996
4988724673517522
8323477255626612

Something like this would do just fine: 这样的事情就可以了:

function random_digits($length) {
    $length = intval($length, 10);
    $output = '';
    for ($i = 0; $i < $length; $i++) {
        $output .= mt_rand(0, 9);
    }
    return $output;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM