0

i am trying to get the year month from 2018-01-06 to till day using the php datetime object using the code

function getMonths(){
    $st_date = new DateTime('2019-01-01');
    $yms = array($st_date);
    while($st_date < new DateTime()){
        array_push($yms, $st_date->add(new DateInterval('P1M')));
    }
    print_r($yms);
}

But the ouput is showing the same values on all the items in the array $yms

Array
(
[0] => DateTime Object
    (
        [date] => 2019-03-01 00:00:00
        [timezone_type] => 3
        [timezone] => Asia/Kolkata
    )

[1] => DateTime Object
    (
        [date] => 2019-03-01 00:00:00
        [timezone_type] => 3
        [timezone] => Asia/Kolkata
    )
....

)

1 Answer 1

2

You push into an array references to the same object. As a result all items show the same time. Use clone to make new one based on a source object data

 function getMonths(){
    $st_date = new DateTime('2019-01-01');
    $yms = array(clone $st_date);
    while($st_date < new DateTime()){
        array_push($yms, clone $st_date->add(new DateInterval('P1M')));
    }
    print_r($yms);
}

demo

Object Cloning

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

Comments

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.