0

Im a bit confused with this one :-S

Im trying to loop through every day between 2 dates, so have the following code (simplified for debugging):-

<?php
$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );

for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d") . "<br/>";
}
?>

However Im doing some work on the dates, but the $begin date was doing something weird, so I tested its value on each loop:-

<?php
$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );

for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d") . " - " . $begin->format("Y-m-d") . "<br/>";
}
?>

And the $begin value is changed to $i, so output is:-

2015-07-03 - 2015-07-03
2015-07-04 - 2015-07-04
2015-07-05 - 2015-07-05
2015-07-06 - 2015-07-06
2015-07-07 - 2015-07-07
2015-07-08 - 2015-07-08
2015-07-09 - 2015-07-09

I tried setting $begin to $being2:-

<?php
$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );
$begin2 = $being;
for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d") . " - " . $begin2->format("Y-m-d") . "<br/>";
}
?>

But $begin2 is still incremented, even though Im not touching it in the for loop.

Can anyone explain to me why this is happening, and how I can access $begin inside my for loop :-S

2
  • 1
    Assigning an object to another variable simply passes a pointer, so in your examples, $i, $begin and $begin2 all point to the same object. If you want a copy of an object, use clone Commented Dec 31, 2019 at 23:41
  • 1
    Use clone + DateTimeImmutable for avoiding extra surprises. Commented Dec 31, 2019 at 23:43

1 Answer 1

0

as @Nick said in his comment, use clone to make exact duplicate of an object

$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );
$begin2 = clone $begin;
for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d") . " - " . $begin2->format("Y-m-d") . "<br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.