As Carbon is an extension of PHP's built-in DateTime, you should be able to use DatePeriod and DateInterval, exactly as you would with a DateTime object
$interval = new DateInterval('P1D');
$to->add($interval);
$daterange = new DatePeriod($from, $interval ,$to);
foreach($daterange as $date){
echo $date->format("Ymd"), PHP_EOL;
}
EDIT
If you need to include the final date of the period, then you need to modify it slightly, and adjust $to before generating the DatePeriod
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($from, $interval ,$to);
foreach($daterange as $date){
echo $date->format("Ymd"), PHP_EOL;
}
private function getDatesFromRange($date_time_from, $date_time_to)
{
// cut hours, because not getting last day when hours of time to is less than hours of time_from
// see while loop
$start = Carbon::createFromFormat('Y-m-d', substr($date_time_from, 0, 10));
$end = Carbon::createFromFormat('Y-m-d', substr($date_time_to, 0, 10));
$dates = [];
while ($start->lte($end)) {
$dates[] = $start->copy()->format('Y-m-d');
$start->addDay();
}
return $dates;
}
Based on Mark Baker's answer, I wrote this function:
/**
* Compute a range between two dates, and generate
* a plain array of Carbon objects of each day in it.
*
* @param \Carbon\Carbon $from
* @param \Carbon\Carbon $to
* @param bool $inclusive
* @return array|null
*
* @author Tristan Jahier
*/
function date_range(Carbon\Carbon $from, Carbon\Carbon $to, $inclusive = true)
{
if ($from->gt($to)) {
return null;
}
// Clone the date objects to avoid issues, then reset their time
$from = $from->copy()->startOfDay();
$to = $to->copy()->startOfDay();
// Include the end date in the range
if ($inclusive) {
$to->addDay();
}
$step = Carbon\CarbonInterval::day();
$period = new DatePeriod($from, $step, $to);
// Convert the DatePeriod into a plain array of Carbon objects
$range = [];
foreach ($period as $day) {
$range[] = new Carbon\Carbon($day);
}
return ! empty($range) ? $range : null;
}
$period = CarbonPeriod::create('2018-06-14', '2018-06-20');
// Iterate over the period
foreach ($period as $date) {
echo $date->format('Y-m-d');
}
// Convert the period to an array of dates
$dates = $period->toArray();
//To get just an array of dates, follow this.
$period = CarbonPeriod::create('2018-06-14', '2018-06-20');
$p = array();
// If you want just dates
// Iterate over the period and create push to array
foreach ($period as $date) {
$p[] = $date->format('Y-m-d');
}
// Return an array of dates
return $p;