Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sinres's avatar

Filter weekdays + saturday Carbon

Hello Guys,

I have array with days of week.

[
    {
        "date": "2021-11-01"
    },
    {
        "date": "2021-11-02"
    },
    {
        "date": "2021-11-03"
    },
    {
        "date": "2021-11-04"
    },
    {
        "date": "2021-11-05"
    },
    {
        "date": "2021-11-06"
    },
    {
        "date": "2021-11-07"
    }
]

Any I get this date by this code:

CarbonPeriod::create(
                2021-11-01,
                2021-11-07
            );

I know I can use filter method filter('isWeekday') but I will only receive weekdays: 2021-11-01 - 2021-11-05. How I can get this array with weekdays + saturday?

Thanks!

0 likes
8 replies
automica's avatar

can you use $dt->isSunday(); and then filter those from your results?

Sinres's avatar

@automica I can't. Maybe do you know how I can remove only sunday from my array? Date ranges can be weekly or bi-weekly

automica's avatar
automica
Best Answer
Level 54

@Sinres you can filter out the Sundays as follows:

    $dates = CarbonPeriod::since('2021-11-01')->days(1)->until('2021-11-07');

    $datesWithoutSundays = collect($dates)->filter(function ($date) {
        return !$date->isSunday();
    })->map(function ($date) {
        return ['date' => $date->format('Y-m-d')];
    });

returns:

[
  {
    "date": "2021-11-01"
  },
  {
    "date": "2021-11-02"
  },
  {
    "date": "2021-11-03"
  },
  {
    "date": "2021-11-04"
  },
  {
    "date": "2021-11-05"
  },
  {
    "date": "2021-11-06"
  }
]
1 like
Sinres's avatar

@automica Thanks, this is work. What do you think about my solution?

$period = CarbonPeriod::create(
                2021-11-01,
                2021-11-07
            )->filter(function ($period) {
                return !$period->isSunday();
            });

            foreach ($period as $date) {
                $dates[] = $date->format("Y-m-d");
            }

Also work fine

automica's avatar

@Sinres its the same difference. I'd prefer the map rather than the foreach as its a bit cleaner.

collect(CarbonPeriod::since('2021-11-01')->days(1)->until('2021-11-07'))->filter(function ($date) {
        return !$date->isSunday();
    })->map(function ($date) {
        return ['date' => $date->format('Y-m-d')];
    });
MichalOravec's avatar

@automica It should be the same as

$dates = CarbonPeriod::create('2021-11-01', '2021-11-07')->filter(function ($date) {
    return ! $date->isSunday();
})->map(function ($date) {
    return $date->toDateString();
});

$dates = iterator_to_array($dates);

CarbonPeriod has forEach() and map() helper methods.

Or with PHP 7.4:

$dates = CarbonPeriod::create('2021-11-01', '2021-11-07')
    ->filter(fn ($date) => ! $date->isSunday())
    ->map(fn ($date) => $date->toDateString());

$dates = iterator_to_array($dates);
2 likes

Please or to participate in this conversation.