phparraysdatefilteringweekday

Filter multidimensional array of dates to exclude weekends (saturdays and sundays)


I'm looping through an array of days in the current month to generate another array of days that are on or after the current day and this is working well. I now need to exclude/omit any dates if they are a Saturday or a Sunday.

I'm trying to work out if it's possible to include a check for Saturday/Sunday dates, something like:

date('N', strtotime($day)) >= 6);

with my existing code that generates an array:

// Get days for current month
    $day = date("Y-m-d");
    $i = strtotime($day);
    
    array("year" => array("month" => array(days)));
    $allDays = array(
        date('Y', $i) => array(
            date('n') => range(date('d', $i), intval(date('t'))),
        ),
    );

Not sure how to combine the test for a weekend date with this or whether I need to use a for loop etc here?


Solution

  • Assuming you're trying to get all the days excluding weekends for the current month: you could use array_filter() with a callback to get the weekend days and then use array_diff() to create a new array containing only week days:

    $year = date('Y');
    $month = date('n');
    
    $weekend_days = array_filter($allDays[$year][$month], function($d) {
        return (date('N', strtotime(date("Y-m-$d"))) >= 6);
    });
    
    $allDays[$year][$month] = array_diff($allDays[$year][$month], $weekend_days);
    
    print_r($allDays);