I am trying to populate an array of dates between a provided start and end date using the PHP Carbon library. This would be straight forward if the dates did not have a particular sequence..
Here is the scenario:
I need to populate the dates array with four days in each week. For example the sequence of these dates must like so with Tuesday being the day of the start date:
Tuesday, Thursday, Saturday, Sunday So I need a way of getting the start date and adding 2 days then 2 days then 1 day before iterating to the next week.
Is this possible to do using Carbon (CarbonPeriod/CarbonInterval)?
Or would my solution for this need to be a custom implementation?
CodePudding user response:
Why not simply use DateTime::add
in a loop (adding 2 days, then 2 days, then 1 day)?
Here is the documentation
CodePudding user response:
Carbon is perfectly able to do this:
// $startDate as mentioned should be a valid Carbon date pointed to Tuesday
$dates = [];
for ($currentDate = $startDate; $currentDate <= $endDate; ) {
$dates[] = $currentDate;
$currentDate->addDays(2);
$dates[] = $currentDate;
$currentDate->addDays(2);
$dates[] = $currentDate;
$currentDate->addDay();
}