0

I have a date schedule function in PHP which aims to execute only on working days. The code I have at the moment is generating the schedule for all days of the week so the while statement doesn't seem to working and I'm not sure why.

I'm a student, so I'm not very experienced with this kind of thing. Here is the code I have so far:

public static function generate_date_schedule($tasksperdayschedule, $startdate) {
    $schedule = [];

    $date = clone $startdate;

    foreach ($tasksperdayschedule as $numberoftasks) {
        $day = (int)$date->format('N');

        // Skip weekend days.
        while ($day > 5) {
            $date->add(new DateInterval('P1D'));
            $day = (int)$date->format('N');
        }

        $schedule[$date->format(self::DATE_FORMAT)] = $numberoftasks;

        $date->add(new DateInterval('P1D'));
    }

   return $schedule;

It is probably something very small I am missing, but any help would be appreciated! Thanks

Ryan
  • 1
  • 1
  • I checked it and it seems to be working fine and skipping weekends. Can you explain what input and output you are expecting? – Jan.J Aug 05 '15 at 10:35
  • It's a small part of a much larger code base, maybe the problem isn't with this function but lies elsewhere. It's expected to create a schedule which is then passed in elsewhere to send out notifications. – Ryan Aug 05 '15 at 10:43

1 Answers1

1

I think its a simple logical error.

Inside the while loop you're updating $day, but the foreach loop continues to execute the rest of the code.

Better yet, you can avoid the while loop by:

if($day > 5)
    continue;
sidx
  • 640
  • 2
  • 11
  • 28
  • I'll give that a shot and get back to you! Thanks! – Ryan Aug 05 '15 at 11:27
  • Just to be clear if I do it using 'continue', the bottom part of the foreach loop doesn't get executed if day is > 5 - right? – Ryan Aug 05 '15 at 11:32
  • Continue will continue the while loop, not the outer foreach. So where I have it, it is doing nothing. – Ryan Aug 05 '15 at 13:48
  • @Ryan drop the `while` and try it using `if`. I've updated my answer. – sidx Aug 05 '15 at 14:00