Kipras
Kipras

Reputation: 2704

PHP unreference

Lets say i have this code:

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

This will print out 2, because $val was passed to $arr by reference.

My question is : if i passed a value to an array by reference, is there a way to remove that reference later on, 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 this should print out 1 (because the array was cloned, before the referenced variable changed). Howerver, clone does not work with arrays, it only works with objects.

Any ideas? I really have no clue how to do this. I tried writing a recursive copy function, but that didn't work.

Upvotes: 3

Views: 527

Answers (1)

user229044
user229044

Reputation: 239432

You could unset the index and then reassign by-value instead of by reference.

unset($arr['val']);
$arr['val'] = $val;

Upvotes: 4

Related Questions