I want to show a random number between 1,000 and 1,999 with these requirements
What I found so far:
<?php
srand(floor(date('U')) / (60*60*24*7));
$num = 100;
$a = rand() % $num;
echo $a;
echo "<br>";
$b = rand() % $num;
echo $b;
echo "<br>";
$c = rand() % $num;
echo $c;
echo "<br>";
$d = rand() % $num;
echo $d;
echo "<br>";
$e = rand() % $num;
echo $e;
?>
By creating an appropriate seed you can do this without needing to store the result.
You'll want to get the ISO-8601 week-numbering year and the week number. You can generate this with date('oW')
. Today (and until next Monday) that'll return 201638
.
The value out of W
changes every Monday and the value from o
changes every year unless the current day's W
belongs to the prior or next year - in which case that year is used. (In other words the year/week combo will never change in the middle of the week due to the new year.)
Once you have that combo use it to seed your random number generator:
mt_srand((int)date('oW'));
Then pull your random number between your limits. With the fixed seed this'll produce the same value for each of your visitors:
$number = mt_rand(1000, 1999);
Then format it to add the thousands separator and output:
echo number_format($number);
All together, skipping the intermediate variable:
mt_srand((int)date('oW'));
echo number_format(mt_rand(1000, 1999));
Today this outputs 1,331
.
There's no need to store the generated number anywhere as this reliably regenerates the same number for every visitor, every day until the next Monday - at which point you get a new seed and therefore a new random number (until the following Monday, as so on.)
For more information on the functions used see the PHP manual: