php random x digit number

前端 未结 21 2139
耶瑟儿~
耶瑟儿~ 2020-12-04 15:00

I need to create a random number with x amount of digits.

So lets say x is 5, I need a number to be eg. 35562 If x is 3, then it would throw back something like; 463

相关标签:
21条回答
  • 2020-12-04 15:49

    rand(1000, 9999); works more faster than x4 times rand(0,9);

    benchmark:

    rand(1000, 9999)      : 0.147 sec.
    rand(0,9)x4 times     : 0.547 sec.
    

    both functions was running in 100000 iterations to make results more explicit

    0 讨论(0)
  • 2020-12-04 15:51

    Treat your number as a list of digits and just append a random digit each time:

    function n_digit_random($digits) {
      $temp = "";
    
      for ($i = 0; $i < $digits; $i++) {
        $temp .= rand(0, 9);
      }
    
      return (int)$temp;
    }
    

    Or a purely numerical solution:

    function n_digit_random($digits)
      return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
    }
    
    0 讨论(0)
  • 2020-12-04 15:55

    rand or mt_rand will do...

    usage:

    rand(min, max);
    
    mt_rand(min, max);
    
    0 讨论(0)
  • 2020-12-04 15:55

    Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number

    mt_rand(2000,9000) 
    
    0 讨论(0)
  • 2020-12-04 15:55

    This is another simple solution to generate random number of N digits:

    $number_of_digits = 10;
    echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
    

    Check it here: http://codepad.org/pyVvNiof

    0 讨论(0)
  • 2020-12-04 15:57

    The following code generates a 4 digits random number:

    echo sprintf( "%04d", rand(0,9999));
    
    0 讨论(0)
提交回复
热议问题