Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
DisgruntledGoat Avatar asked Jun 20 '11 23:06

DisgruntledGoat


People also ask

How do I clone an array in PHP?

The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

How do I copy an array into another array in PHP?

Using array_push Method: This method pushes the second array element in the first array in-place. $arr1 = array (1, 2); $arr2 = array (3, 4); // arr2 elements are being pushed in the arr1.

Which function is used to copy elements of an array into variables in PHP?

1 Expert Answer Just assign the array to a variable. $array2 = $array1; If you want them to reference each other (So the change in one array will affect the other) use the & character before the variable.


1 Answers

$array = array_merge(array(), $myArray); 
like image 131
erani Avatar answered Oct 09 '22 07:10

erani