Search code examples
phparrayslaraveldate

How to display today and the next four days php


I have an app where I need to display today, and the next four days on.

$daysOn = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Mon'];

$daysOff = [ 'Sat', 'Sun' ];

$today = date("N", strtotime('today'));

$yesterday = date("N", strtotime('yesterday'));

$daysOnRearranged = array_merge(array_slice($daysOn, $today), array_slice($daysOn, 0, $yesterday));

This is currently showing me:

Monday, Monday, Tuesday, Wednesday, Thursday.

I need to show today, and the next for days on.

Any ideas?


Solution

  • Here I am using the strtotime ability to workout the date using a string like "Today + 1 day". I am also using the character "D" that returns 'A textual representation of a day, three letters'. You can change the "D" to a "l" if you want the full name of the day.

    $nextDays = [];
    
    for ($i = 0; $i <= 4; $i++) {
    
            $nextDays[] = date("D", strtotime("today + $i day"));
    }
    
    var_dump($nextDays);
    

    To remove weekends:

    $nextDays = [];
    $daysOff = ["Sat", "Sun"];
    
    $n = 0; 
    
    do {
        $day = date("D", strtotime("today + $n day"));
        if (!in_array($day, $daysOff)) { // Check if the above $day is _not_ in our days off
            $nextDays[] = $day;
        }
        $n ++; // n is just a counter
    } while (count($nextDays) <= 4); // When we have four days, exit.
    
    var_dump($nextDays);