Home > other >  PHP: find dates every week for different days
PHP: find dates every week for different days

Time:02-20

I am trying to solve a problem I am looking for hours into. My students have special courses and I am trying to find the dates.

For example:

Student 1 in Class A: every Monday from Jan 1st till April 1st

Student 2 in Class B: every Wednesday from April 1st until June...

So I programmed a function in which I can pass info like begin, end, weekday to show me the dates:

function tkcheck ($beginnfunc,$endfunc,$daycheck)
{
    $begin = new DateTime($beginnfunc);
    $end = new DateTime($endfunc);
    $interval = new DateInterval('P1W');
    $period = new DatePeriod($begin, $interval, $end);
    foreach ($period as $date) {    
        $dayw = $date->modify($daycheck);
        if ($dayw < $end) {
            $daystring = $dayw->format ('d-m-Y');
        $q1day1[] = $daystring;
        
        }
    }
}
tkcheck ('2022-02-20','2022-04-01','next Wednesday');

print_r($q1day1);

But print_r does not show me any information when I try to use my function tkcheck...

Maybe some here might help me, thank you!

CodePudding user response:

$q1day1 is scoped within the function. It is not accessible out of the function.

To fix this return the variable.

function tkcheck ($beginnfunc,$endfunc,$daycheck)
{
    $begin = new DateTime($beginnfunc);
    $end = new DateTime($endfunc);
    $interval = new DateInterval('P1W');
    $period = new DatePeriod($begin, $interval, $end);

    foreach ($period as $date) {    
        $dayw = $date->modify($daycheck);

        if ($dayw < $end) {
            $daystring = $dayw->format ('d-m-Y');
            $q1day1[] = $daystring;
        }
    }

    return $q1day1;
}

$result = tkcheck ('2022-02-20','2022-04-01','next wednesday');

print_r($result);

See Variable Scope for more info.

CodePudding user response:

The special feature of this solution is simply to create a Date::Interval from 'next Monday'.

$start = date_create('Jan 1st 2022')->modify('-1 Day');
$end = date_create('Apr 1st 2022');
$interval = DateInterval::createFromDateString('next Monday');
$period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
$dateArray = iterator_to_array ($period);

echo '<pre>'.var_export($dateArray,true).'</pre>';

The modification with "-1 Day" is necessary to record a Monday that falls exactly on the start date.

  •  Tags:  
  • php
  • Related