Is there a function to make a copy of a PHP array to another?
I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an obj
When you do
$array_x = $array_y;
PHP copies the array, so I'm not sure how you would have gotten burned. For your case,
global $foo;
$foo = $obj->bar;
should work fine.
In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.
Creates a copy of the ArrayObject
<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;
// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);
?>
from https://www.php.net/manual/en/arrayobject.getarraycopy.php
This is the way I am copying my arrays in Php:
function equal_array($arr){
$ArrayObject = new ArrayObject($arr);
return $ArrayObject->getArrayCopy();
}
$test = array("aa","bb",3);
$test2 = equal_array($test);
print_r($test2);
This outputs:
Array
(
[0] => aa
[1] => bb
[2] => 3
)
If you have only basic types in your array you can do this:
$copy = json_decode( json_encode($array), true);
You won't need to update the references manually
I know it won't work for everyone, but it worked for me
array_merge() is a function in which you can copy one array to another in PHP.
I like array_replace (or array_replace_recursive).
$cloned = array_replace([], $YOUR_ARRAY);
It works like Object.assign from JavaScript.
$original = [ 'foo' => 'bar', 'fiz' => 'baz' ];
$cloned = array_replace([], $original);
$clonedWithReassignment = array_replace([], $original, ['foo' => 'changed']);
$clonedWithNewValues = array_replace([], $original, ['add' => 'new']);
$original['new'] = 'val';
will result in
// original:
{"foo":"bar","fiz":"baz","new":"val"}
// cloned:
{"foo":"bar","fiz":"baz"}
// cloned with reassignment:
{"foo":"changed","fiz":"baz"}
// cloned with new values:
{"foo":"bar","fiz":"baz","add":"new"}