'Show rotation of tweets using current day of month

I'm trying to create something that will check the date and produce a different variable result depending on the date today.

This is my current code:

<?php 
for($i = 0; $i <= 25; $i++) 
    $dates[] = date("d", strtotime( "+$i days"));

foreach ($dates as $today) {
    if (in_array($today, array('01', '05', '09', '14', '19', '24'), true)) {
        $tweet = "one";
    }
    if (in_array($today, array('02', '06', '10', '15', '20', '25'), true)) {
        $tweet = "two";
    }
    if (in_array($today, array('03', '07', '11', '16', '21'), true)) {
        $tweet = "three";
    }
    if (in_array($today, array('04', '08', '12', '17', '22'), true)) {
        $tweet = "four";
    }
}
echo $tweet;
?>

Problem is that even if the date changes it always echos "four", what am I missing?



Solution 1:[1]

Using a battery of in_array() calls is an approach that lacks creativity and certainly isn't D.R.Y.

Declare a lookup array and perform a simple modulus calculation on the current day value. When dividing the day number by 4, days 1, 5, 9, 13, etc will return 1; days 2, 6, 10, 14, etc will return 2; days 3, 7, 11, 15, etc will return 3; and days 4, 8, 12, 16, etc will return 0 (because there is no remainder in the calculation).

That return value can then be used to access the lookup value corresponding to that key. This is a much more professional approach.

Code: (Demo)

$tweetLookup = [
    'Four',
    'One',
    'Two',
    'Three',
];
for ($i = 0; $i <= 25; $i++) {
    echo $i . ": " . $tweetLookup[date("d", strtotime( "+$i days")) % 4];
    echo "\n";
}

Output:

0: One
1: Two
2: Three
3: Four
4: One
5: Two
6: Three
7: Four
8: One
9: Two
10: One
11: Two
12: Three
13: Four
14: One
15: Two
16: Three
17: Four
18: One
19: Two
20: Three
21: Four
22: One
23: Two
24: Three
25: Four

To make the code even more dynamic, replace the hardcoded 4 with count($tweetLookup). This will afford you to manage the script behavior by only manipulating the data source -- you'll never need to touch the processing logic.

P.S. I would recommend using DateTime objects, but that is a secondary topic for this question.

Solution 2:[2]

Because you overwrite $tweet in each iteration of the loop, it means only the last iteration is actually available. The last iteration will be today + 25 days, which would be the 12th December.

12 causes the assignment of $tweet to four and since that's the last iteration, that's what $tweet be be equal to after the loop ends.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mickmackusa
Solution 2 Jonnix