I'm not sure yet if this is a bug or a feature of PHP, but be very careful when mixing arrays with the PHP reference operator (&). I just spent many hours tracking down a bug where changing an array copy was also changing the original array. It took several more hours to figure out that accessing an array by reference caused subsequent copies of that array to also be linked by reference!

Here's a simple piece of PHP that illustrates what I found (PHP Version 5.1.6):

This code copies an array and changes one of it's values...as expected the original array doesn't change:

<?php
$array1 = array(1,2);
$array2 = $array1;
$array2[1]=22; // Change one value, $array1 remains unchanged
print_r($array1);
?>

Produces:

Array
(
[0] => 1
[1] => 2
)

 

But, if we add a reference to one of the array elements the behavior changes, even though the reference isn't used!:

<?php
$array1 = array(1,2);
$x = &$array1[1]; // Unused reference
$array2 = $array1;
$array2[1]=22;
print_r($array1);
?>

Produces:

Array
(
[0] => 1
[1] => 22
)

The var_dump() function gives a hint to what's going on. You would normally expect that a variable assignment wouldn't change the source, but in this case it does. It seems a PHP array reference changes the assignment source!:

<?php
$array1 = array(1,2);
var_dump($array1);
$x = &$array1[1]; // Unused reference changes source $array1
var_dump($array1);
?>

Produces:

array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
array(2) {
[0]=>
int(1)
[1]=>
& int(2)
}

Notice the & int(2) indicating that the source array has been modified . I'm not sure yet if this is a bug or a feature of PHP. I'm leaning towards the bug side though since this doesn't happen with regular variables:

<?php
$y1 = 1;
$x = &$y1; // Unused reference does NOT affect source
$y2 = $y1;
$y2=22;
print_r($y1);
?>

Produces:

1

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:

<?php
$array1 = array(1,2);

$x = &$array1[1]; // Unused reference
$array2 = $array1;
unset($x); // Array copy is now unaffected by above reference
$array2[1]=22;
print_r($array1);
?>

Produces:

Array
(
[0] => 1
[1] => 2
)

I'll update this if I find out more...

I added a comment about this to the PHP manual. Others may add related comments: http://us3.php.net/manual/en/language.references.php