phpdatelaravel-5php-carbon

Iterating Carbon date inside loop


In my Laravel project I want to create a array of next 7 days dynamically. I have following setup:

    $pickup_dates = [];
    $today = Carbon::today();
    for ($i = 0; $i < 7; $i++) {
      $pickup_dates[] = $today->addDay();
    }
    dd($pickup_dates);

But when I use dd to dump data my output as follows:

Array
(
[0] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[1] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[2] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[3] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[4] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[5] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

[6] => Carbon\Carbon Object
    (
        [date] => 2017-08-09 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )

)

As you can see it outputs same date, but I want to date sequence of the next 7 days. What I want to achieve is this:

Can you tell me what is the wrong with this code? Or is there any other way to achieve this?


Solution

  • You are working with same Carbon object that's why you are getting out put like that.

    Try this

    $pickup_dates = [];
    $today = Carbon::today()->toDateString();
    for ($i = 0; $i < 7; $i++) {
        $pickup_dates[]=Carbon::parse($today);
          $today = Carbon::parse($today)->addDay()->toDateString();
    }
    dd($pickup_dates);
    

    Out put as
    enter image description here