php - Copied array is being affected by changing the original array -


i'm quite stunned weird problem. i'm trying add records $array, copying $cloned , passing $cloned batchinsert, which, design, adds key _id array. see unexpected behavior when try dump contents of original array, should have no reference $cloned (copied) array. instead, _id appear both in $array , $cloned, quite weird , can't imagine what's happening.

this code gives me expected bahaviour

$array = array(); for($i = 1; $i <= 5; $i++) {     $array[] = $i;     $cloned = $array;     passtofunction($cloned);     print_r($array); // expecting not have added array }  function passtofunction(&$b) {     $b["test"] = new obj(); }  class obj {     public $test = "test"; } 

results, correctly, in

array (     [0] => 1 ) array (     [0] => 1     [1] => 2 ) array (     [0] => 1     [1] => 2     [2] => 3 ) . . . . 

however, in case use mongodb driver,

$m = new mongoclient(); $db = $m->selectdb("test"); $users = $db->users;  for($i = 1; $i <= 5; $i++) {         $array[] = array("number" => $i);         $cloned = $array;         $users->batchinsert($cloned);         print_r($array); } 

gives me following output:

array (     [0] => array         (             [number] => 1             [_id] => mongoid object                 (                     [$id] => 55a7f2bbd04aa45b228b4567                 )          )  ) 

note _id key, shouldn't in original array, in copied one. missing?


Comments