Skip to content
Advertisement

Laravel Carbon, problem with getting the last ten days

I need to get the date of the last ten days. To do so I do this

$start = Carbon::now()->subDays(10);
for ($i = 0; $i <= 9; $i++) {
     $day = $start->addDays($i)->format('Y-m-d');
     print $day.' ';
}

This is the result!!

2020-02-01 2020-02-02 2020-02-04 2020-02-07 2020-02-11 2020-02-16 2020-02-22 2020-02-29 2020-03-08 2020-03-17

Why it skips some days?

Advertisement

Answer

Because you’re adding 1 day, then 2 days, then 3 days, then 4 days… You should just add one day each time:

$start = Carbon::now()->subDays(10);
for ($i = 0; $i <= 9; $i++) {
     $day = $start->addDays(1)->format('Y-m-d');
     print $day.' <br/>';
}

Outputs:

2020-02-02
2020-02-03
2020-02-04
2020-02-05
2020-02-06
2020-02-07
2020-02-08
2020-02-09
2020-02-10
2020-02-11

Edit: addDays() modifies the variable it is called on, so the code actually works without $day:

$start = Carbon::now()->subDays(10);
for ($i = 0; $i <= 9; $i++) {
  $start->addDays(1);
  print $start->format('Y-m-d') . '<br/>';
}

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement