tags:

views:

1568

answers:

3

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.

+3  A: 

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.

chaos
A: 

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
Reinis I.
+2  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.

troelskn
+1: very simple and clear explanations, thanks!
Marco Demajo