简体   繁体   中英

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

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

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

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.

    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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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