0

I have the following PHP code:

$todaysdate = date_create();
for ($i = date_sub(date_create(),date_interval_create_from_date_string("1 month")); $i <= $todaysdate; $i = date_add($i,date_interval_create_from_date_string("1 day"))) {
    $json['message'][] = $i;
}

The counter $i doesnot increment at all. $i remains at Object { date="2017-03-02 20:00:55.000000", timezone_type=3, timezone="Asia/Kolkata"}

9
  • 1
    Try "+1 day" at the end of the for loop. Commented Mar 1, 2017 at 14:42
  • @shaun tried it. no luck. Commented Mar 1, 2017 at 14:47
  • it works for me on phptester.net, prints whole of feb and the 1st of march Commented Mar 1, 2017 at 14:50
  • @RobertPounder I get $json with 28 occurances but all the dates in the 28 arrays are 2017-03-02 14:55:37.031447 is that what you get Commented Mar 1, 2017 at 14:57
  • @RobertPounder I'm using PHP 5. unfortunately, my dates are not incrementing. same situation as riggsfolly. Commented Mar 1, 2017 at 15:13

1 Answer 1

1

As suggested by RiggsFolly, I updated the code to the following:

$todaysdate = date_create();
for ($i = date_sub(date_create(),date_interval_create_from_date_string("1 month")); $i <= $todaysdate; $i = date_add($i,date_interval_create_from_date_string("+1 day"))) {
    $json['message'][] = $i->format('d-m-Y');
}

It's now working. The only change was the line $json['message'][] = $i->format('d-m-Y');

Sign up to request clarification or add additional context in comments.

1 Comment

What about using the DatePeriod class, e.g. $todaysdate =date_create();$month= new DatePeriod(date_sub($todaysdate,date_interval_create_from_date_string("1 month")),date_interval_create_from_date_string("1 day"),$todaysdate);foreach($month as $day){...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.