php random x digit number

You can use rand() together with pow() to make this happen:

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);

This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.

If 005 also is a valid example you'd use the following code to pad it with leading zeros:

$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

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

e.g.

rand ( 10000 , 99999 );

for your 5 digit random number


Here is a simple solution without any loops or any hassle which will allow you to create random string with characters, numbers or even with special symbols.

$randomNum = substr(str_shuffle("0123456789"), 0, $x);

where $x can be number of digits

Eg. substr(str_shuffle("0123456789"), 0, 5);

Results after a couple of executions

98450
79324
23017
04317
26479

You can use the same code to generate random string also, like this

$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);

Results with $x = 11

FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr

You can use rand($min, $max) for that exact purpose.

In order to limit the values to values with x digits you can use the following:

$x = 3; // Amount of digits
$min = pow(10,$x);
$max = pow(10,$x+1)-1);
$value = rand($min, $max);

Treat your number as a list of digits and just append a random digit each time:

function n_digit_random($digits) {
  $temp = "";

  for ($i = 0; $i < $digits; $i++) {
    $temp .= rand(0, 9);
  }

  return (int)$temp;
}

Or a purely numerical solution:

function n_digit_random($digits)
  return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}