I am trying to make random numbers that are exactly 15 characters long and positive using php. I tried rand(100000000000000, 900000000000000)
but it still generates negatives and numbers less than 15. Is there another function I am missing that can do this, or should I just use rand(0, 9)
15 times and concatenate the results?
Asked
Active
Viewed 5,006 times
3

Mike
- 1,718
- 3
- 30
- 58
-
2For what it's worth, `rand` isn't broken, it's just that the numbers you are using are larger then the size of an `int` on your machine which is why you're seeing odd results. – Mike Park Jan 02 '13 at 23:55
-
possible duplicate of [Using long int in PHP](http://stackoverflow.com/questions/8647125/using-long-int-in-php) – Peter O. Jan 03 '13 at 01:32
4 Answers
9
$i = 0;
$tmp = mt_rand(1,9);
do {
$tmp .= mt_rand(0, 9);
} while(++$i < 14);
echo $tmp;

Tigger
- 8,980
- 5
- 36
- 40
-
1int mt_rand ( int $min , int $max ) is the way to go. I would use this answer. +1 – ROY Finley Jan 02 '13 at 23:52
-
-
1@ZOLDIK : Before [PHP 7.1 there were issues](https://stackoverflow.com/a/28760905/1291879). These have now been resolved with `rand()` becoming an alias for `mt_rand()`. – Tigger Jun 08 '20 at 23:41
3
You are using a 32 bit platform. To handle these integers, you need a 64bits platform.
You can do the rand two times and save it as a string, like this:
$num1 = rand(100000,999999);
$num2 = rand(100000,999999);
$num3 = rand(100,999);
$endString = $num1.$num2.$num3;
PS. I like tiggers solution better than mine.

Green Black
- 5,037
- 1
- 17
- 29
-
safe to go till 2bil (10chr) so a mt_rand for 7 digits and another one for 8 digits will do it, also 99999999 instead of 9000000 – CSᵠ Jan 02 '13 at 23:54
-
You are right. I wasn't sure about the number, so I played it safe. – Green Black Jan 02 '13 at 23:56
-
1
1
Here you go.
function moreRand($len) {
$str = mt_rand(1,9);
for($i=0;$i<$len-1;$i++) {
$str .= mt_rand(0, 9);
}
return $str;
}
echo moreRand(15);
Edit: If you want to shave .00045s off your execution time,
function randNum() { return abs(rand(100000000000000, 900000000000000)); }

Josh Brody
- 5,153
- 1
- 14
- 25
-
1Keep in mind this could return 0 as the first 'digit', which technically would be a 14 digit number. – Supericy Jan 02 '13 at 23:59
-
1
Keep in mind that this will return a string, not an actual integer value.
function randNum($length)
{
$str = mt_rand(1, 9); // first number (0 not allowed)
for ($i = 1; $i < $length; $i++)
$str .= mt_rand(0, 9);
return $str;
}
echo randNum(15);

Supericy
- 5,866
- 1
- 21
- 25