Reputation: 681
So I need to make unique purchase number of mobile game. Each user's buying of in-app-purchase item record should be attached by unique long type 19 digits numbers from php code and stored to mysql DB.
But how can I actually make random 19 digits numbers?
I tried like this but errors.
$num_str = sprintf("%19d", mt_rand(1, 9999999999999999999));
Upvotes: 3
Views: 5024
Reputation: 31749
You have to do something like -
$num_str = sprintf("%10d", mt_rand(1, mt_getrandmax())).sprintf("%9d", mt_rand(1, mt_getrandmax()));
if (strlen($num_str) < 19)
$num_str = str_pad($num_str, 19, rand(0, 9), STR_PAD_RIGHT);
else if(strlen($num_str) > 19)
$num_str = substr($num_str, 0, 19);
echo $num_str;
The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32. This is because if max is greater than the value returned by mt_getrandmax(), the output of the random number generator must be scaled up.
Upvotes: 0
Reputation: 1981
you can also try this:
function random19() {
$number = "";
for($i=0; $i<19; $i++) {
$min = ($i == 0) ? 1:0;
$number .= mt_rand($min,9);
}
return $number;
}
echo random19();
which would output some random 19 numbers: 6416113158912395605
Upvotes: 4