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

  • 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`](https://www.php.net/manual/en/language.oop5.cloning.php) – Nick Dec 31 '19 at 23:41
  • 1
    Use `clone` + [DateTimeImmutable](https://www.php.net/manual/en/class.datetimeimmutable.php) for avoiding extra surprises. – LazyOne Dec 31 '19 at 23:43

1 Answers1

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/>";
}
jtnptl89
  • 11
  • 4