3

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?

Mike
  • 1,718
  • 3
  • 30
  • 58
  • 2
    For 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 Answers4

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
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
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
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