0

I'm working on a website where the user can create some events every X days (where X is the name of a day in the week). Then, he needs to enter the number of events he wants to create in the future.

For example, the user selects every Monday and Tuesday and decides to create 150 events.

Here is the code I have made until now :

// Init the date counter            
$cpt_date_found = 0;

// Number of date to find
$rec_occ = 150;

// Init an ending date far in the future        
$endDate = strtotime('+10 years', time());

// Loop over the weeks
for($i = strtotime('Monday', strtotime(date("d.m.Y"))); $i <= $endDate; $i = strtotime('+1 week', $i)) {

    // -- Monday date found, create the event in the database

    $cpt_date_found++;

    // Break the loop if we have enough dates found
    if($cpt_date_found == $rec_occ) {
        break;
    }

}

This code finds the date of every Monday in the future and breaks the loop once we have reached the number of occurrences the user specified.

I have entered an ending date far in the future to make sure I can break the loop before the end of the occurrences count specified by the user.

First I'm not sure about the "quality" of my code... I know that breaking the loop is not the best idea and am wondering if another solution would better fit my needs.

Then, instead of repeating the loop more times if the user specified several days (let's say, Monday, Tuesday and Friday), is there a way to loop one time for every provided days?

Thanks!

fraxool
  • 3,199
  • 4
  • 31
  • 57

1 Answers1

0

The following code will loop over a period of 5 years. For each week in those 5 years it will generate a DatePeriod containing each day of that week. It will compare each of those days to your preset array with days you are looking for. You can then generate your event after which the code will countdown for a certain amount of times. If the counter hits zero, you are done.

$searchDates = array('Mon', 'Tue', 'Fri');
$amountOfTimes = 27;

$startDate = new DateTime();
$endDate = new DateTime('next monday');
$endDate->modify('+5 years');

$interval = new DateInterval('P1W');
$dateRange = new DatePeriod($startDate, $interval ,$endDate);

// Loop through the weeks
foreach ($dateRange as $weekStart) {
    $weekEnd = clone $weekStart;
    $weekEnd->modify('+6 days');

    $subInterval = new DateInterval('P1D');

    // Generate a DatePeriod for the current week
    $subRange = new DatePeriod($weekStart, $subInterval ,$weekEnd);
    foreach ($subRange as $weekday) {
        if (in_array($weekday, array('Mon', 'Fri', 'Sun'))) {
            // Create event

            // Countdown
            $amountOfTimes--;
        }

        if ($amountOfTimes == 0) {
            break;
        }
    }
}
Peter
  • 8,776
  • 6
  • 62
  • 95