1

I would like to create an array which consists of ascending date objects. I tried the following code:

$dat=date_create_from_format("Y-m-d H:i:s", "2014-11-01 00:00:00");
for ($i=0; $i<=2; $i++) {
    $ar[$i]=$dat;
    $dat->modify('+1 day');
}
print_r($ar);

The result is three times the same date:

Array
(
    [0] => DateTime Object
        (
            [date] => 2014-11-04 00:00:00.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [1] => DateTime Object
        (
            [date] => 2014-11-04 00:00:00.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [2] => DateTime Object
        (
            [date] => 2014-11-04 00:00:00.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

)

But what I would like to get is:

   Array
    (
        [0] => DateTime Object
            (
                [date] => 2014-11-01 00:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/Berlin
            )

        [1] => DateTime Object
            (
                [date] => 2014-11-02 00:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/Berlin
            )

        [2] => DateTime Object
            (
                [date] => 2014-11-03 00:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/Berlin
            )

    )

Someone has an idea? Probably a newbie-thing ;-)

1 Answer 1

1

As $dat is an obejct, all items in $ar store references to this object. So, when this object changes ($dat->modify()), all references immediately see this changes. To create different object, you can clone source object:

$dat = date_create_from_format("Y-m-d H:i:s", "2014-11-01 00:00:00");
for ($i = 0; $i <= 2; $i++) {
    $ar[$i] = clone $dat;
    $dat->modify('+1 day');
}
print_r($ar);

Here clone operator takes you current $dat object and makes a copy of it. So when you change $dat again, copy doesn't know about it.

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.