Chunking Carbon dates into consecutive blocks

  laravel, laravel-collection, php, php-carbon

I have a Laravel collection of Carbon dates:

$dates = collect([
  Carbon::parse('2020-09-18'),
  Carbon::parse('2020-09-21'),
  Carbon::parse('2020-09-22'),
  Carbon::parse('2020-10-13'),
  Carbon::parse('2020-10-14'),
  Carbon::parse('2020-10-15'),
  Carbon::parse('2020-11-02'),
  Carbon::parse('2020-11-03'),
  Carbon::parse('2020-11-04'),
  Carbon::parse('2020-11-05')
]);

I want to split these into chunks where the dates are consecutive weekdays. I’ve managed to use chunkWhile to split the collection where the dates are either before or after:

$chunks = $dates->chunkWhile(function ($date, $key, $chunk) {
  return $date->diffInDays($chunk->last()) < 2;
});

However this breaks when a weekend is in between. In the above example the dates ‘2020-09-18’, ‘2020-09-21’, ‘2020-09-22’ are consecutive weekdays but are Fri, Mon and Tue so are split by my current formula. How can I adjust it to ignore weekends.

Source: Laravel

Leave a Reply