PHP misunderstanding

Let's say I have this code:

$ val = 1;
$ arr = Array ();
$ arr ['val'] = & $ val;
$ val = 2;
echo $ arr ['val'];

This will print 2 because $ val was passed to $ arr for the link.

My question is: if I passed the value to the array by reference, is there a way to delete this link later by making it a simple copied value? To make it clearer, I would like something like this:

$ val = 1;
$ arr = Array ();
$ arr ['val'] = & $ val;

$ arr ['val'] = clone $ arr ['val']; 
// Or better yet:
$ arr = clone $ arr;

$ val = 2;
echo $ arr ['val'];

And that should print 1 (because the array was cloned before the changed reference variable was changed). Howerver, the clone does not work with arrays, it only works with objects.

Any ideas? I really don't know how to do this. I tried to write a recursive copy function, but that didn't work.

+3
source share
1 answer

You can unsetpointer, and then reassign by value instead of reference.

unset($arr['val']);
$arr['val'] = $val;
+4
source

Source: https://habr.com/ru/post/1790950/


All Articles