Mike
Mike

Reputation: 1738

Random number that is 15 characters long and positive

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?

Upvotes: 3

Views: 5264

Answers (4)

Josh Brody
Josh Brody

Reputation: 5363

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)); }

Upvotes: 1

Supericy
Supericy

Reputation: 5896

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

Upvotes: 1

Green Black
Green Black

Reputation: 5084

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.

Upvotes: 3

Tigger
Tigger

Reputation: 9130

$i = 0;
$tmp = mt_rand(1,9);
do {
    $tmp .= mt_rand(0, 9);
} while(++$i < 14);
echo $tmp;

Upvotes: 9

Related Questions