php copying array elements by value, not by reference

By : oym

I have the following code:

$data['x'] = $this->x->getResults();  

$data['y'] = $data['x'];

//some code here to modify $data['y']
//this causes (undesirably) $data['x] to be modified as well

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?


Update: $this->x->getResults(); returns an object array. So I can then do something like: $data['x'][0]->date_create ...

Update: my latest attempt to clone the array looks something like this:

   $data['x'] = $this->x->getResults();     
   $data['y'] = $data['y'];
   foreach($data['x'] as $key=>$row) {
       $data['y'][$key]->some_attr = clone $row->some_attr;

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..).

UPDATE: Just solved it!: inside the foreach loop I just needed to change the line to:

$data['y'][$key] = clone $row;

And it works! Thanks to everyone for the help.

By : oym


You could use this function to copy multidimensional arrays containing objects.

By : uKolka

If you are working with objects, you might want to take a look at clone, to create a copy of an object, instead of a reference.

Here is a very short example :

First, with an array, it works by value :

$data['x'] = array(
    'a' =

Not simple. Read about clone

BUT! if your elements are not objects and not refence type variables you have no problem.

Example for reference types:


This video can help you solving your question :)
By: admin