views:

2428

answers:

1

So $array is an array of which all elements are references.

I want to append this array to another array called $results (in a loop), but since they are references, PHP copies the references and $results is full of identical elements.

So far, the best working solution is:

$results[] = unserialize(serialize($array));

which I fear to be incredibly inefficient. Is there a better way to do this?

+2  A: 

You can use the fact that functions dereferences results when returning, for exemple here $d will still have a reference to $a ($d[0][0] == 'somethingelse') while $c will have a cloned value ($c[0][0] == 'something')

$a = 'something';
$b = array(&$a);

$c = array();
$d = array();

function myclone($value)
{
    return $value;
}

$c[] = array_map('myclone', $b);
$d[] = $b;

$a = 'somethingelse';

echo $c[0][0]; // something, values were cloned
echo $d[0][0]; // somethingelse
Lepidosteus
I did a bit of benchmarking and unserialize(serialize()) is slightly faster
Chad