Generate time ranges with Carbon
In PHP there is no need to be clever with arrays, especially if you are using Laravel and Collections. There is a function for allmost anything. No need to invent the wheel.
The same goes to dates, and especially the excellent Carbon library with adds some nice features on PHP’s native DateTime
.
My goal was to create a list of times between like 10:00 and 14:00 with 15 minute intervals. After some Googling there was some clever solutions until I discovered PHP’s DateInterval
, but if you use CarbonInterval
, which is build on top of DateInterval
you get a nice one-liner like this:
$intervals = CarbonInterval::minutes($timeStep)->toPeriod($start, $end);
Then you will get an array of Carbon-object which you can use however you want:
foreach ($intervals as $date) {
dump($date->format('H:i'))
}