Generate an N-digit random number

后端 未结 7 1554
清酒与你
清酒与你 2020-12-05 09:49

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 <

相关标签:
7条回答
  • 2020-12-05 10:14

    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

    0 讨论(0)
  • 2020-12-05 10:20

    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
    )
    
    0 讨论(0)
  • 2020-12-05 10:25
        <?php
    //If you wanna generate only numbers with min and max length:
            function intCodeRandom($length = 8)
            {
              $intMin = (10 ** $length) / 10; // 100...
              $intMax = (10 ** $length) - 1;  // 999...
    
              $codeRandom = mt_rand($intMin, $intMax);
    
              return $codeRandom;
            }
    ?>
    
    0 讨论(0)
  • 2020-12-05 10:29

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 10:36

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 10:37

    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.

    `

    0 讨论(0)
提交回复
热议问题