'Generate a random number with pre-defined length PHP

I'm trying to create a function using mt_rand() in order to generate a truly random number, since rand() just isn't suffice.

The problem is I need to pre-define the length of the number, say I need a 10 digit random number.

Anyway, I've been messing around and this is what I've come up with:

    function randomNumber($length) {
        $min = str_repeat(0, $length-1) . 1;
        $max = str_repeat(9, $length);
        return mt_rand($min, $max);   
    }

In theory that should work (as far as I can tell), but it doesn't. The length is completely random and it also throws out negative values.

Any ideas?



Solution 1:[1]

just sepcify the range to rand method , if you need 4 digit random number then just use it as

rand(1000,9999);

Solution 2:[2]

Short and sweet:

I'm assuming only legitimate numbers, not strings like 00010. Try useing the size of your number to be:

  $min = pow(10, $length - 1) ;
  $max = pow(10, $length) - 1;
  return mt_rand($min, $max);   

The only one that doesn't work is when length is 1, a single digit number '0' won't be a possible value to be returned.

Solution 3:[3]

Here is what I'm using:

function random_number($length)
{
    return join('', array_map(function($value) { return $value == 1 ? mt_rand(1, 9) : mt_rand(0, 9); }, range(1, $length)));
}

One line, nice and simple! The number will never start with 0 and allows 0 at any other place.

Solution 4:[4]

function randomNDigitNumber($digits)
{
  $returnString = mt_rand(1, 9);
  while (strlen($returnString) < $digits) {
    $returnString .= mt_rand(0, 9);
  }
  return $returnString;
}

The first line ensures that no "0" precedes any number, for instance values like 012, 0598... will be discarded, the rest is easy

Solution 5:[5]

function randomNumber($length) {
    $min = 1 . str_repeat(0, $length-1);
    $max = str_repeat(9, $length);
    return mt_rand($min, $max);   
}

you have your concat 1 in the wrong spot, your range is this for $length=2: {01,99} - sometimes its 01-09, that is represented as 1-9 not 01-09. Just start from 10: {10,99} will be your range.

Solution 6:[6]

Use this for strings of a certain length with both letters and numbers. Tested.

protected function randomToken($length = 4, $result='') {

    for($i = 0; $i < $length; $i++) {

        $case = mt_rand(0, 1);
        switch($case){

            case 0:
                $data = mt_rand(0, 9);
                break;
            case 1:
                $alpha = range('a','z');
                $item = mt_rand(0, 25);

                $data = strtoupper($alpha[$item]);
                break;
        }

        $result .= $data;
    }

    return $result;
}

Solution 7:[7]

You shouldn't start with the length constraining the random numbers. Rather accumulate a long enough output, then cut it to the right length:

while (strlen($value) < $length) {
    $value .= str_pad(mt_rand(00000, 99999), 5, "0", STR_PAD_LEFT);
}
// as pairs of five were added before, eventually remove some again
return substr($value, 0, $length);

The padding should be there, because even zeros are randomly generated and should be retained.

Solution 8:[8]

Assuming you are using a small range and don't want to generate the same number twice, how about this:

function random(int $len): int
{
    static $track = [];
    
    $min = 1 . str_repeat(0, $len - 1);
    $max = str_repeat(9, $len);
    $num = mt_rand($min, $max);
    
    // if was generated before, try again
    if (in_array($num, $track))
    {
        return random($len);
    }
    
    // store and return
    return $track[] = $num;
}

Keeping track of the generated randoms via static variable, which is only initiated once, will prevent generating the same number twice, but note that if you exceed the number of unique possibilities dictated by $len you will get stuck in an infinite loop. For example you can't call random(1) more than 9 times because $len is 1 and there are only 9 unique possibilities (excluding 0) so you need to have an idea about how many randoms you are going to need or choose big enough $len and not worry about it.

Solution 9:[9]

if the environment is local there is no need to make a random number and mt_rand is like rand but four times faster

    protected function generateRandomNumber(int $length = 6)
    {
        $rand = '';
        $env = env('APP_ENV');
        for ($i = 1; $i <= $length; $i++) {
            $rand .= ($env == 'local') ? $i : mt_rand(($i == 1) ? 1 : 0, 9);
        }

        return (int) $rand;
    }

Solution 10:[10]

Here I need a random number of length 10, Here is what I'm using:

$characters = rand(1111111111, 9999999999);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swapnil Ghone
Solution 2
Solution 3 Jazzer
Solution 4 King Leon
Solution 5 Michael
Solution 6 Peter B
Solution 7 mario
Solution 8
Solution 9 sajadsholi
Solution 10 train_fox