title: php copying array elements by value, not by reference
body: <p>I have the following code:</p>
  
  <pre><code>$data['x'] = $this-&gt;x-&gt;getResults();  
  
  $data['y'] = $data['x'];
  
  //some code here to modify $data['y']
  //this causes (undesirably) $data['x] to be modified as well
  </code></pre>
  
  <p>I guess since all the elements of $data are themselves references, modifying $data['y'] also modifies $data['x']..which is NOT what I want.  I want $data['x'] to remain the same.  Is there any way to dereference the elements here so that I can copy the elements by value?</p>
  
  <p>Thanks.</p>
  
  <p>Update: $this->x->getResults(); returns an object array.  So I can then do something like: $data['x'][0]->date_create ...</p>
  
  <p><strong>Update</strong>:
  my latest attempt to clone the array looks something like this:</p>
  
  <pre><code>   $data['x'] = $this-&gt;x-&gt;getResults();     
     $data['y'] = $data['y'];
     foreach($data['x'] as $key=&gt;$row) {
         $data['y'][$key]-&gt;some_attr = clone $row-&gt;some_attr;
     }
  </code></pre>
  
  <p>Am I way off here? I keep getting a "__clone method called on non-object" error.  From reading the responses it seems like my best option is to iterate over each element and clone it (which is what I was trying to do with that code..).</p>
  
  <p><strong>UPDATE</strong>: Just solved it!: inside the foreach loop I just needed to change the line to:</p>
  
  <pre><code>$data['y'][$key] = clone $row;
  </code></pre>
  
  <p>And it works! Thanks to everyone for the help.</p>