Zeth
Zeth

Reputation: 2578

Echoing a random element from array each day

I'm trying to make a simple function, that echos a random element from an array, but it should change, every time that day changes. Example:

$myarray = array(
  'foo',
  'bar',
  'winnie',
  'the',
  'poo');

echo array_rand($myarray);

This would print a random thing from the array, every time the page loads. But I would like for it to only change each day. I would like for it to work, so if you load the page Monday at 8:00 and Monday at 17:00 (edit1: it's the same random output that has been pulled, regardless of, if it's user A or user B that sees it), then you would see the same (random) element, from the array. But if the page was loaded at Tuesday at 13:00, then a different element from the array would be printed. Edit1: The timezone should be the easiest to program (since it's not significant). So I assume that the servers timezone would be the easiest.

I thought about getting integer-value of the date, and then use modulo to the length of the array (since the length of the array will get more and more values with time). Something along the lines of echo $myarray[date(U) % count($myarray)] (this hasn't been tested and wont work, since it's the second since 1970 (or whenever) and not the days, but it was just to give an idea of what kind of solution I had in mind).

There is no database on the site, so I can't store the value in a database.

Edit2: So if we have user A and user B, that each load the page each day of the week. Then I'm looking for user A to receive something along these lines:

Monday: foo
Tuesday: the
Wednesday: foo
Thursday: poo
Friday: winnie
Saturday: winnie
Sunday: bar

And if user B load the page, then he will see the same values as user A (I assume this is the easiest way to set it up as well).

-- end of edit2 --

Edit3: It could also just be a txt-file or a json-file that is stored on the FTP-server, where each day, a new line of this txt-file is printed. It doesn't need to be an array.

-- end of edit3 --

Upvotes: 0

Views: 129

Answers (1)

Steve
Steve

Reputation: 20469

You can do this with a simple text file on the server:

$randoms = array(
  'foo',
  'bar',
  'winnie',
  'the',
  'poo'
);
$file = 'todaysrandom.dat';
if(file_exists($file) && date('d-m-Y', filemtime($file)) == date('d-m-Y')){
    //if the file exists, and was last updated today, return the contents of the file:
    $todaysRandom = file_get_contents($file);

}else{
    //else create todays value, and save it to the file
    $todaysRandom = $randoms[rand(0,count($randoms)-1)];
    file_put_contents($file, $todaysRandom);
}
echo $todaysRandom;

Upvotes: 2

Related Questions