Is there a function to make a copy of a PHP array to another?

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 object to a global outside it.


In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:

$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);

Will yield:

array(0) {
}

Whereas:

$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);

Yields:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

You could get confused by intricacies such as ArrayObject , which is an object that acts exactly like an array. Being an object however, it has reference semantics.

Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.


PHP will copy the array by default. References in PHP have to be explicit.

$a = array(1,2);
$b = $a; // $b will be a different array
$c = &$a; // $c will be a reference to $a

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 just as well for any type of array (including mixed type).

function array_clone($array) {
    return array_map(function($element) {
        return ((is_array($element))
            ? call_user_func(__FUNCTION__, $element)
            : ((is_object($element))
                ? clone $element
                : $element
            )
        );
    }, $array);
}
链接地址: http://www.djcxy.com/p/9844.html

上一篇: 单身之间有什么区别

下一篇: 有没有一个函数可以将PHP数组的副本拷贝到另一个?