I'm quite stunned with this weird problem. I'm trying to constantly add records to some $array
, copying it to $cloned
and then passing $cloned
to batchInsert
, which, by design, adds key _id
to the array. I see unexpected behavior when I try to dump contents of the original array, which should have no reference with $cloned
(copied) array. Instead, _id
appear both in $array
and $cloned
, which is quite weird and I 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 to have anything added to that 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 I 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 the _id
key, which shouldn't be in the original array, just in the copied one. What am I missing?