PAPADOC PAPADOC - 2 months ago 8
PHP Question

Extracting dates from date range

Part of my answer was answered by dynamic:
How to extract every Monday and every fortnightly Monday from a range of two dates in PHP?

I've added a foreach loop to print all the mondays in this example:

$start = strtotime('2016-09-05');
$end = strtotime('2016-09-30');

$mondays=array();
$tuesdays=array();

while( $start <= $end ) {

if ( date('N',$start)==1 )
$mondays[]=$start;
$start += 86400;

}
foreach ($mondays as $item) {
print date("D. Y-m-d", ($item));
print ("<br>");
}


and i get these results:
enter image description here

But how do i add an else/if statements to display the tuesdays for example

if the date begins with $start = strtotime('2016-09-06');

I want it to show:
enter image description here

Thanks.

Answer

In this code, we first find the DayOfWeek, and then find all dof in range:

// Data

$StartDate = strtotime('2016-09-06');
$EndDate   = strtotime('2016-09-30');

$DayOfWeek = date("l", $StartDate); // Determine day of week

$LoopDate = $StartDate;

// Find all DayOfWeek's Between Start and End

$Result = [$StartDate];

while (true) {
    $NextDayOfWeek = strtotime("next " . $DayOfWeek, $LoopDate);

    if ($NextDayOfWeek > $EndDate) {
        break;
    }

    $Result[] = $LoopDate = $NextDayOfWeek;
}

// Print Result

/**
 | 2016-09-06
 | 2016-09-13
 | 2016-09-20
 | 2016-09-27
 */
foreach( $Result as $Row ) {
    echo date("Y-m-d", $Row) . '<br/>';
}