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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With