Search code examples
phprandomnumbers

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

  • If by “a truly random number” you mean a cryptographically secure random number, make sure to use random_int instead of mt_rand. mt_rand is not based on a CSPRNG. If you don’t know whether you need a CSPRNG, use random_int anyway – it’s not slow.

    If you want an n-digit numeric string, that's exactly what you should get: n individual digits.

    function random_digits($length) {
        $result = '';
    
        for ($i = 0; $i < $length; $i++) {
            $result .= random_int(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.