Jirka Kopřiva
Jirka Kopřiva

Reputation: 3089

php strange behavior while changing value

Having this snippet for buffering events.

$temp = array();

while ($row = $source)
{
  $temp[] = $row;

   // `add_day` means how many of next days add to buffer

   $d = new DateTime($row->date);

   for ($i = 0; $i < $row->add_day; $i++)
   {
      $d->modify('+1 day');          

      $row->date = $d->format('Y-m-d');

      $temp[] = $row;

      // print_r($row) --> It's OK. `date` has proper value.
   }
}

While tracking single event, everything seems to be fine. But in the result - $temp array, all rows from forcycle have the same date value. (the last one.)

E.G.

$data = { date: '2015-07-01', add_day: 2 }

Result:

$temp[0] = { date: '2015-07-03'} 
$temp[1] = { date: '2015-07-03'}
$temp[2] = { date: '2015-07-03'}  

Where I am doing a mistake??

Upvotes: 1

Views: 49

Answers (1)

John Conde
John Conde

Reputation: 219804

You keep overwriting the value for that date in your object. Since that array has references to the same object they all return the same value.

for ($i = 0; $i < $row->add_day; $i++)
{
    $d->modify('+1 day');          
    // Here you keep updating your object to have the new date
    $row->date = $d->format('Y-m-d');
    $temp[] = $row;
}

Cloning those objects is one way to work around this:

for ($i = 0; $i < $row->add_day; $i++)
{
    $d->modify('+1 day');    
    $tempObj = clone $row;      
    $tempObj->date = $d->format('Y-m-d');
    $temp[] = $tempObj;
}

Upvotes: 3

Related Questions