Andrew Charlton
Andrew Charlton

Reputation: 251

How can I add a random number to each item in foreach loop but to stay the same for 1 day

I'm trying to assign a different random number on each item in a foreach loop but I'd like the number to stay the same for one day.

I've tried simply adding <?php echo rand(0,20); ?> but this obviously just creates a random number per each refresh.

Is there anyway I could keep the same random number per each item for one day without adding it to the database.

for example:

item 1 = 2
item 2 = 18
item 3 = 13
item 4 = 6

Stays the same for 1 day then changes

Upvotes: 0

Views: 1734

Answers (3)

Johann Bauer
Johann Bauer

Reputation: 2606

Maybe you could try something like:

$not_random_at_all = base_convert(md5($item . date('l jS \of F Y')), 16, 10);

Where $item is the number of your item (or anything that identifies the item).

It just converts the MD5-Hash of the current date concatenated with your item number to integer.

That means a different random number for every item daily.

Remember that MD5 is not a random number generator and your results might bot be as random as they can be.

Upvotes: 0

rubo77
rubo77

Reputation: 20845

$seed = floor(time()/86400);
srand($seed);
foreach($list as $item){
  echo $item.rand(0,20);
}

or to obtain the same value of rand in a determined time interval. Another Example: you have an array of 20 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).

$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,19)];

You obtain the same value every time you load the page all the 24h period.

Upvotes: 0

Patrick
Patrick

Reputation: 881

You can do this by programming your own random number generator. This guide shows you how to do it.

Note: Code below from sitepoint

class Random {

    // random seed
    private static $RSeed = 0;

    // set seed
    public static function seed($s = 0) {
        self::$RSeed = abs(intval($s)) % 9999999 + 1;
        self::num();
    }

    // generate random number
    public static function num($min = 0, $max = 9999999) {
        if (self::$RSeed == 0) self::seed(mt_rand());
        self::$RSeed = (self::$RSeed * 125) % 2796203;
        return self::$RSeed % ($max - $min + 1) + $min;
    }

}

To call it

// set seed
Random::seed(42);

// echo 10 numbers between 1 and 100
for ($i = 0; $i < 10; $i++) {
    echo Random::num(1, 100) . '<br />';
}

Now set your seed based on the current date with the php date function

// set seed based on date with 
Random::seed(date("z") + 1);

This will give you the same numbers every year. If you don't want this, use the seed variable of rubo77. With this version you can ensure to get the same number on different machines (can't guarantee that with srand).

Upvotes: 1

Related Questions