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

rickbolton's avatar

For loop save each hour into array between 2 datetime's

Here is my code

$start = Carbon::now();
$end = Carbon::now()->AddHours(7);
$data = [];
for($d = $start;$d < $end;$d->AddHour()){
    $data[] = $d;
};
return $data;

This returns the end date for each loop into the array rather than each hour up to the end date.

[ { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" }, { "date": "2015-10-26 18:00:39.000000", "timezone_type": 3, "timezone": "UTC" } ]

0 likes
4 replies
mstnorris's avatar
Level 55

@rickbolton I set up a simple /date route in a new app to test out your code. See below, I added toDateTimeString(). When you call ->addHours(n) it doesn't change the actual date (value of $d) (what you were expecting), it just modifies it. You need to print it out to get the value.

get('date', function() {
    $start = Carbon::now();
    $end = Carbon::now()->addHours(7);
    $data = [];
    for($d = $start;$d < $end;$d->addHour()){
        $data[] = $d->toDateTimeString(); // this line here!
    };
    return $data;
});

This returns:

[
"2015-10-26 11:44:58",
"2015-10-26 12:44:58",
"2015-10-26 13:44:58",
"2015-10-26 14:44:58",
"2015-10-26 15:44:58",
"2015-10-26 16:44:58",
"2015-10-26 17:44:58"
]
1 like
rickbolton's avatar

That's great thank you! All makes sense so thanks for your help and explanation. :)

pmall's avatar

Yep, you were always adding the same reference of the date object into the array. Now you add a string so it works.

digitaloutback's avatar
$values = collect(CarbonInterval::minutes(60)->toPeriod(today(), today()->endOfDay()))->map->format('H:i');

Please or to participate in this conversation.