user9555022
user9555022

Reputation:

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?

Upvotes: 0

Views: 80

Answers (2)

beingalex
beingalex

Reputation: 2476

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);

Upvotes: 1

Rahul
Rahul

Reputation: 18577

On days check condition to be checked inside for loop.
Please have a look into below snippet and running code.

<?php

function pr($arr = [])
{
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

$daysOn  = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Mon'];
$daysOff = ['Sat', 'Sun'];
$today     = date("N", strtotime('today'));
$nextDays = [];
$j = $i = 0;

while($j != 4){ // until it found next 4 working days
    $day = date('D', strtotime("today +$i day")); // it will keep checking for next working days
    if(in_array($day, $daysOn)){ // will check if incremental day is in on days or not
        $nextDays[] = $day; // it will add on days in result array
        $j++;
    }
    $i++;
}
pr($nextDays);die;

Here is working demo.

EDIT

Above snippet is for checking on days.
You can check for OFF Days like below.

while($j != 4){
    $day = date('D', strtotime("today +$i day"));
    if(!in_array($day, $daysOff)){
        $nextDays[] = $day;
        $j++;
    }
    $i++;
}
pr($nextDays);die;

Upvotes: 0

Related Questions