简体   繁体   中英

Generate a fixed random number in a range based on a string in PHP

I need to generate a random number or hash that will be the same each time based on a string. This is done easily enough with the function crc32, however, I need it to be an integer between a range because the random number will be picking an item out of an array.

Here's the code I have so far:

$min=0;
$max=count($myarray);
$number = crc32("Joe Jones");

$rnd = '.'.(string)$number;
//(Int((max-min+1)*Rnd+min))
$rand = round(($max-$min+1)*$rnd+$min);

echo $rand;

It seems to work, but it always picks lower numbers. It never picks the higher numbers.

Just use mod (%). $x % $n will ensure an output between 0 and $n-1 for any $x .

$myArray=range(1,1000);
$max=count($myArray); //1000
$number = crc32("Joe Jones"); //2559948711
$rand=$number % $max; //711

Also just a note about crc32: It may return a negative number if you run it on a 32 bit platform, so you may optionally want to do abs(crc32($input))

Your crc32 function is producing a negative number. Change the line as follows:

$number = abs(crc32("Joe Jones"));

This turns that negative number in to a positive one. Also, you might want to consider multiplying that number if your your array count is is low. How high that goes is up to you.

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