Reputation: 395
I want to generate 6 digit numbers. Now this work great BUT occasionally it generates 4 digit numbers. Not often but some times it does. Why??
$num = rand(000000, 999999);
Upvotes: 1
Views: 6351
Reputation: 22
http://php.net/manual/en/function.rand.php
Note :
Warning
min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax() Otherwise, rand() may return poor-quality random numbers.
So, an other note :
Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.
Upvotes: 0
Reputation: 11
As everyone else said, you could change $num = rand(000000, 999999);
to $num = rand(100000, 999999);
, but there might be a case where you need a number that has 6 digits, but whose value is below 100000. Ex. 001103. You can still use $num = rand(000000, 999999);
but you would use something like:
$num = rand(000000, 999999);
$print_num = sprintf("%06d", $num);
This would not change the number, it will only give it a 6 digit format.
Upvotes: 0
Reputation: 471
rand(000000, 999999)
is equal to rand(0, 999999)
It will return a number between 0 and 999999. In 90% of all cases the number is between 100000 and 999999 and you will have a 6 digit number. That is why it works for you most of the time
But in 10% of all cases, the number will be smaller than 100000 and only contain 1 to 5 digits (all numbers between 1 and 99999..not hard to figure out that 1 or 2 digits are still less propable then 4 or 5 digits)
To solve your problem you have to get a number from rand(100000, 999999)
, but this won't contain any numbers starting with 0! The first digit will always be from 1 and 9.
The other answers already show nice solutions for getting 6 digits from 0 to 9. Another easy one would just be:
for($i = 0; i < 6; i++)
$rand_digit[$i] = rand(0,9);
Upvotes: 1
Reputation: 6787
If you want to generate numbers from 000000
to 999999
with 6-digit padding, you can use the str_pad
function.
$rand = rand(0, 999999);
echo str_pad($rand, 6, '0', STR_PAD_LEFT);
Upvotes: 4