I'm creating an array of dates that won't be selectable in a calendar. The following works, although the way I've gone about it is quite long-winded.
I was wondering if there is a more elegant way of getting all the dates in a month, where dates don't fall on various days a project does run on. It's probably more clear from the example...
$project_days_this_month = [];
$month_array = [];
$month = date('n');
$year = date('Y');
$project_days = [1, 6]; // days of week the project runs on
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
// create an array of days in month
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $year.'-'.$month.'-'.$day; //format date
$month_array[] = $date;
}
// get project days in month
foreach ($project_days as $pd) {
//loop through all days
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $year.'-'.$month.'-'.$day; //format date
$day_number_of_week = date('N', strtotime($date));
// add project days to array
if($day_number_of_week == $pd){
$project_days_this_month[] = $date;
}
}
}
// get the difference - these will be non project days
$non_project_days = array_diff($month_array, $project_days_this_month);
print_r($non_project_days);
Are there any PHP functions that can be used here that would might make this code more concise?
cal_days_in_month()
is not shown. You should familiarize yourself with PHP'sDateTime
,DatePeriod
,DateInterval
, etc. classes. \$\endgroup\$