How to clone an array of objects in PHP?
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;
}
You need to clone objects to avoid having references to the same object.
function array_copy($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
As suggested by AndreKR, using array_map() is the best way to go if you already know that your array contains objects:
$clone = array_map(function ($object) { return clone $object; }, $array);
$array = array_merge(array(), $myArray);