Skip to content
Advertisement

Get the next x days excluding weekends and show them all

I am having some difficulties display the next x number of days excluding weekends. The basic code is here which displays all days:

<?php

for($i = 0; $i < 8; $i++) {
    echo date('D M j', strtotime("$i day"));
}

?>

I cant then get it to do a continue:

<?php

for($i = 0; $i < 8; $i++) {
    $day = date('N', strtotime("$i day"));
    if($day == '6' || $day == '7') continue;
    echo date('D M j', strtotime("$i day"));
}

?>

But this obviously skips the weekends completely and I don’t get x returned days. I have tried reducing the number by 1 but just get timeouts so guessing this is not the way to go.

Advertisement

Answer

As CBroe already pointed out, use a variable for the number of days you want to iterate. When you get a saturday or sunday then increment that variable by one. E.g.

<?php

$x = 8;
for($i = 0; $i < $x; $i++) {
    $day = date('N', strtotime("$i day"));
    if($day == '6' || $day == '7') {
        $x++;
        continue;
    }
    echo date('D M j', strtotime("$i day"));
}

?>

The output would always be $x weekdays, for today it would be

Fri Jan 22Mon Jan 25Tue Jan 26Wed Jan 27Thu Jan 28Fri Jan 29Mon Feb 1Tue Feb 2
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement