Is there a function 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.
Is there a function 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.
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.
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
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.