php random x digit number

前端 未结 21 2136
耶瑟儿~
耶瑟儿~ 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:35

    you can generate any x-digit random number with mt_rand() function. mt_rand() much faster with rand() function syntax : mt_rand() or mt_rand($min , $max).

    read more

    example : <?php echo mt_rand(); ?>

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

    I usually just use RAND() http://php.net/manual/en/function.rand.php

    e.g.

    rand ( 10000 , 99999 );
    

    for your 5 digit random number

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

    you people really likes to complicate things :)

    the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.

    so, just append the larger portion of that number as a math sum, not string.

    e.g.

    $x = "102384129" . complex_3_digit_random_string();

    simply becomes

    $x = 102384129000 + rand(0, 999);

    done.

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

    This function works perfectly with no repeats and desired number of digits.

    $digits = '';
    function randomDigits($length){
        $numbers = range(0,9);
        shuffle($numbers);
        for($i = 0; $i < $length; $i++){
            global $digits;
            $digits .= $numbers[$i];
        }
        return $digits;
    }
    

    You can call the function and pass the number of digits for example:

    randomDigits(4);
    

    sample results:

    4957 8710 6730 6082 2987 2041 6721

    Original script got from this gist

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

    this simple script will do

    $x = 4;//want number of digits for the random number
    $sum = 0;
    
    
    for($i=0;$i<$x;$i++)
    {
        $sum = $sum + rand(0,9)*pow(10,$i);
    
    }
    
    echo $sum;
    
    0 讨论(0)
  • 2020-12-04 15:43

    do it with a loop:

    function randomWithLength($length){
    
        $number = '';
        for ($i = 0; $i < $length; $i++){
            $number .= rand(0,9);
        }
    
        return (int)$number;
    
    }
    
    0 讨论(0)
提交回复
热议问题