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?
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.
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.
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.
$array = array_merge(array(), $myArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With