Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
Karl Avatar asked Oct 31 '12 23:10

Karl


2 Answers

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

rand(1000,9999);
like image 87
Swapnil Ghone Avatar answered Oct 15 '22 01:10

Swapnil Ghone


Unless you have one of those quantum-static thingies, you can't get a truly random number. On Unix-based OSes, however, /dev/urandom works for "more randomness", if you really need that.

Anyway, if you want an n-digit number, that's exactly what you should get: n individual digits.

function randomNumber($length) {
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $result .= mt_rand(0, 9);
    }

    return $result;
}

The reason your existing code isn't working is because 0000...01 is still 1 to mt_rand, and also that mt_rand's range isn't infinite. The negative numbers are integer overflows.

like image 26
Ry- Avatar answered Oct 15 '22 01:10

Ry-