How to choose a random index based on the current time

Given an array of length N, how do I pick a random index based on the current time. Basically I wanted to generate a random integer from 0 to N based on the current time. Can this be done mathematically?

+3


source to share


2 answers


You can seed a random number generator with a derived value from time()

:

mt_srand(time() / 30 / 60); // reseed every 30 minutes

echo mt_rand(0, N);

      

Without a random number generator, you can simply use modulo:



echo (time() / 30 / 60) % N;

      

Note that the output mt_rand()

may include N, while the module version is missing.

+1


source


Think you are looking for something like this:



<?php

    $numbers = array(1,2,3,4,5,6,7,8,9,10);
    $random = date('i')/5 % count($numbers);
    echo  $random . "<br />";
    echo $numbers[$random];

?>

      

+1


source







All Articles