Mt_rand () always gives me the same number

I have a problem with this function, always mine mt_rand()gives 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'));

$hexalways changing, 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

+4
source share
1 answer

Your problem is that you always get the float value in the variable $hex. And the function mt_srand(), as you can see in manual :

void mt_srand ([ int $ seed])

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

, 0, "" .

, :

var_dump($hex);

:

float(1.0908183557664E+77)

, , , :

var_dump((int)$hex);

, 0.


, , float, - , manual:

PHP , float . , , , float.

:

echo PHP_INT_MAX;

int, :

28192147483647      //32 bit
9223372036854775807 //64 bit

EDIT:

, - ?

, , , , PHP_INT_MAX, , - . , , .

- :

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

str_split(), shuffle() implode() 7 , array_slice().

hexdec(), mt_srand().

7 ? , , PHP_INT_MAX.

+5

All Articles