views:

56

answers:

2

Suppose I have an array of nodes (objects). I need to create a duplicate of this array that I can modify without affecting the source array. But changing the nodes will affect the source nodes. Basically maintaining pointers to the objects instead of duplicating their values.

// node(x, y)
$array[0] = new node(15, 10);
$array[1] = new node(30, -10);
$array[2] = new node(-2, 49);

// Some sort of copy system
$array2 = $array;

// Just to show modification to the array doesn't affect the source array
array_pop($array2);
if (count($array) == count($array2))
  echo "Fail";    

// Changing the node value should affect the source array
$array2[0]->x = 30;
if ($array2[0]->x == $array[0]->x)
   echo "Goal";

What would be the best way to do this?

+2  A: 

If you use PHP 5:

Have you run your code? It is already working, no need to change anything. I get:

Goal

when I run it.

Most likely this is because the values of $array are already references.

Read also this question. Although he OP wanted to achieve the opposite, it could be helpful to understand how array copying works in PHP.

Update:

This behaviour, when copying arrays with objects, the reference to the object is copied instead the object itself, was reported as a bug. But no new information on this yet.


If you use PHP 4:

(Why do you still use it?)

You have to do something like:

$array2 = array();

for($i = 0; $i<count($array); $i++) {
    $array2[$i] = &$array[$i];
}
Felix Kling
Ahhh, I didn't actually test the code. I was expecting having to use `copy` or something like that. Thanks for the info. How does this work when passing through functions?
St. John Johnson
@StJohn Johnson: What do you mean with passing through functions? An object passed to a function as parameter? This should also be passed by reference (in PHP 5). See also here: http://devzone.zend.com/article/1714
Felix Kling
A: 

it is some time that I don' write PHP code, but does the code

// Some sort of copy system
$array2 = $array;

actually work?

Don't you have to copy each element of the array in a new one?

Giovanni Di Milia
No, you don't have to copy every element. The documentation says: *Array assignment always involves value copying.* http://php.net/manual/en/language.types.array.php
Felix Kling
you are right...during my answer I was thinking how to keep pointers instead of a copy of the objects...
Giovanni Di Milia