Search code examples
phparraysobjectclone

How to clone an array of objects in PHP?


I have an array of objects. I know that objects get assigned by "reference" and arrays by "value". But when I assign the array, each element of the array is referencing the object, so when I modify an object in either array the changes are reflected in the other.

Is there a simple way to clone an array, or must I loop through it to clone each object?


Solution

  • References to the same objects already get copied when you copy the array. But it sounds like you want to shallow-copy deep-copy the objects being referenced in the first array when you create the second array, so you get two arrays of distinct but similar objects.

    The most intuitive way I can come up with right now is a loop; there may be simpler or more elegant solutions out there:

    $new = array();
    
    foreach ($old as $k => $v) {
        $new[$k] = clone $v;
    }