Peter
Peter

Reputation: 3495

How to set the state of random in php to be the same for an hour

I know this would be possible in python, and could most likely pull it off, but I can't seem to find much in PHP to do with random states

I would like a random item to be pulled out of a list, and running the code again within the hour will still return the same item

I've got the date to the nearest hour, and the code to get a random value from the list, I just need the bit linking the two

$hour = date('mdYh', time());
$url = $website."/".$lines[rand(1, count($lines)-1)];

Thanks :)

Upvotes: 0

Views: 104

Answers (1)

goat
goat

Reputation: 31813

If you really want to use the random number generator, then

srand(mktime(null, 1, 1));
echo $lines[array_rand($lines)];

I'm using mktime() to make a number that increases once per hour. Then, I use that number to seed php's random number generator. array_rand() uses the RNG, and so it will pick the same entry for the hour.

But...php's RNG is global across the entire program, and so any other random numbers needed in other parts of the code will be very predictable(they too, will be the same for the hour). Beware.

Also, I haven't thought about how this will behave around daylight savings time.

Upvotes: 1

Related Questions