1

I have this code :

$eindejaar = date('Y-m-d', strtotime("last day of last year"));
$beginjaar = date('Y-m-d',strtotime("first day of last year"));
$begin = new DateTime( $beginjaar);
$end   = new DateTime( $eindejaar );

foreach($array AS $installatie)
{


       for($i = $begin; $i <= $end; $i->modify('+1 day')){

        etc etc ...

Now if I initialize the datetime objects outside the foreach-loop, the for-loop goes only once. If I place them inside the foreach-loop, it works like a charm and I get an iteratrion of the for-loop for every foreach:

$eindejaar = date('Y-m-d', strtotime("last day of last year"));
$beginjaar = date('Y-m-d',strtotime("first day of last year"));


foreach($array AS $installatie)
{

  $begin = new DateTime( $beginjaar);
  $end   = new DateTime( $eindejaar );

    for($i = $begin; $i <= $end; $i->modify('+1 day')){

   etc etc ...

I can see that in the first example the datetime object $begin gets changed after 1 iteration, so that's why the second example works (I initialize it again) Maybe a basic question, but I don't get why the object gets changed

Elrond
  • 23
  • 3
  • _"but I don't get why the object gets changed"_ - because that's what `modify` _does_ ...? – CBroe Sep 21 '21 at 09:25
  • @Cbroe : I get why it changes the $i, but not the $begin – Elrond Sep 21 '21 at 09:32
  • Because it is still the same object instance, the fact that you have different variable names "pointing" to it, doesn't change that. https://stackoverflow.com/a/185939/1427878 – CBroe Sep 21 '21 at 09:37

0 Answers0