I need to create a random number with x amount of digits.
So lets say x is 5, I need a number to be eg. 35562 If x is 3, then it would throw back something like; 463
rand(1000, 9999);
works more faster than x4 times rand(0,9);
benchmark:
rand(1000, 9999) : 0.147 sec.
rand(0,9)x4 times : 0.547 sec.
both functions was running in 100000 iterations to make results more explicit
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);
}
rand
or mt_rand
will do...
usage:
rand(min, max);
mt_rand(min, max);
Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number
mt_rand(2000,9000)
This is another simple solution to generate random number of N digits:
$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
Check it here: http://codepad.org/pyVvNiof
The following code generates a 4 digits random number:
echo sprintf( "%04d", rand(0,9999));