Generate a random number with pre-defined length PHP

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.


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.


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

rand(1000,9999);

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.