Generate an N-digit random number

2019-01-17 10:09发布

I want to generate a 6 digit random number using the PHP mt_rand() function.

I know the PHP mt_rand() function only takes 2 parameters: a minimum and a maximum value.

How can I do that?

7条回答
在下西门庆
2楼-- · 2019-01-17 10:46

as far as understood, it should be like that;

function rand6($min,$max){
    $num = array();

    for($i=0 ;i<6;i++){
    $num[]=mt_rand($max,$min);

    }
return $num;
}
查看更多
一夜七次
3楼-- · 2019-01-17 10:48

Examples:

print rand() . "<br>"; 
//generates and prints a random number
print rand(10, 30); 
//generates and prints a random number between 10 and 30 (10 and 30 ARE included)
print rand(1, 1000000); 
//generates and prints a random number between on and one million

More Details

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-17 10:57

You can use the following code.

  <?php 
  $num = mt_rand(100000,999999); 
  printf("%d", $num);
  ?>

Here mt_rand(min,max);
min = Specifies the lowest number to be returned.
max = Specifies the highest number to be returned.

`

查看更多
祖国的老花朵
5楼-- · 2019-01-17 10:59

Something like this ?

<?php 
$a = mt_rand(100000,999999); 
?>

Or this, then the first digit can be 0 in first example can it only be 1 to 9

for ($i = 0; $i<6; $i++) 
{
    $a .= mt_rand(0,9);
}
查看更多
Evening l夕情丶
6楼-- · 2019-01-17 11:04

You can do it inline like this:

$randomNumbersArray = array_map(function() {
    return mt_rand(); 
}, range(1,6));

Or the simpliar way, with a function:

$randomNumbersArray = giveMeRandNumber(6);

function giveMeRandNumber($count)
{
    $array = array();
    for($i = 0; $i <= $count; $i++) {
        $array[] = mt_rand(); 
    }
}

These will produce an array like this:

Array
(
    [0] => 1410367617
    [1] => 1410334565
    [2] => 97974531
    [3] => 2076286
    [4] => 1789434517
    [5] => 897532070
)
查看更多
放我归山
7楼-- · 2019-01-17 11:06

If the first member nunmber can be zero, then you need format it to fill it with zeroes, if necessary.

<?php 
$number = mt_rand(10000,999999);
printf("[%06s]\n",$number); // zero-padding works on strings too
?>

Or, if it can be form zero, you can do that, to:

<?php 
$number = mt_rand(0,999999);
printf("[%06s]\n",$number); // zero-padding works on strings too
?>
查看更多
登录 后发表回答