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
simple and makes deep copy breaking all links
$new=unserialize(serialize($old));
private function cloneObject($mixed)
{
switch (true) {
case is_object($mixed):
return clone $mixed;
case is_array($mixed):
return array_map(array($this, __FUNCTION__), $mixed);
default:
return $mixed;
}
}
Define this:
$copy = create_function('$a', 'return $a;');
Copy $_ARRAY to $_ARRAY2 :
$_ARRAY2 = array_map($copy, $_ARRAY);
If you have an array that contains objects, you need to make a copy of that array without touching its internal pointer, and you need all the objects to be cloned (so that you're not modifying the originals when you make changes to the copied array), use this.
The trick to not touching the array's internal pointer is to make sure you're working with a copy of the array, and not the original array (or a reference to it), so using a function parameter will get the job done (thus, this is a function that takes in an array).
Note that you will still need to implement __clone() on your objects if you'd like their properties to also be cloned.
This function works for any type of array (including mixed type).
function array_clone($array) {
return array_map(function($element) {
return ((is_array($element))
? array_clone($element)
: ((is_object($element))
? clone $element
: $element
)
);
}, $array);
}
I know this as long time ago, but this worked for me..
$copied_array = array_slice($original_array,0,count($original_array));
$arr_one_copy = array_combine(array_keys($arr_one), $arr_one);
Just to post one more solution ;)