简体   繁体   中英

mt_rand() gives me always the same number

I have a problem with this function always my mt_rand() give me the same number:

$hex = 'f12a218a7dd76fb5924f5deb1ef75a889eba4724e55e6568cf30be634706bd4c'; // i edit this string for each request
$hex = hexdec($hex);    
mt_srand($hex);
$hex = sprintf("%04d", mt_rand('0','9999'));

$hex is always changed, but the result is always the same 4488 .

Edit

$hex = str_split($hex);
$hex = implode("", array_slice($hex, 0, 7));
mt_srand($hex);
$number = sprintf("%04d", mt_rand('0','9999'));

http://php.net/manual/en/function.mt-srand.php

Your problem is, that you always end up with a float value in your variable $hex . And the function mt_srand() as you can also see in the manual :

void mt_srand ([ int $seed ] )

Expects an integer. So what it does is, it simply tries to convert your float value to an integer. But since this fails it will always return 0.

So at the end you always end up with the seed 0 and then also with the same "random" number.

You can see this if you do:

var_dump($hex);

output:

float(1.0908183557664E+77)

And if you then want to see in which integer it will end up if it gets converted you can use this:

var_dump((int)$hex);

And you will see it will always be 0.


Also if you are interested in, why your number ends up as float, it's simply because of the integer overflow, since your number is way too big and accoding to the manual :

If PHP encounters a number beyond the bounds of the integer type , it will be interpreted as a float instead . Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

And if you do:

echo PHP_INT_MAX;

You will get the max value of int, which will be:

28192147483647      //32 bit
9223372036854775807 //64 bit

EDIT:

So now how to fix this problem and still make sure to get a random number?

Well the first thought could be just to check if the value is bigger than PHP_INT_MAX and if yes set it to some other number. But I assume and it seems like you will always have such a large hex number.

So I would recommend you something like this:

$arr = str_split($hex);
shuffle($arr);
$hex = implode("", array_slice($arr, 0, 7));

Here I just split your number into an array with str_split() , to then shuffle() the array and after this I implode() the first 7 array elements which I get with array_slice() .

After you have done this you can use it with hexdec() and then use it in mt_srand() .

Also why do I only get the first 7 elements? Simply because then I can make sure I don't hit the PHP_INT_MAX value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM