Deep copy of PHP array

Hi,

What’s the most efficient way to create a deep copy of a PHP array?

Sample code would be appreciated.

Many thanks,

Bardi

What is a ‘deep’ copy?

If I may venture a guess I’d say it’s a copy of the array and all the nested arrays in it.

If I’m not mistaken PHP always copies arrays by value, not by reference, so to make copy you could just do $copy=$array;

I’m guessing Javascript background OP? (In javascript all assignments are by reference)

In PHP only objects are copied by reference normally. So it’s quite simple

$copy = $array;

If you do need an assignment by reference you can do this

$copy &= $array;

With objects this becomes much trickier.

$copy = clone($object);

If you need to deep clone an object (that has objects within it) then you’ll have to write a magic __clone method for the object that you are about to clone. It’s messy to say the least - so avoid having objects that have object collections unless you don’t need to clone them.