3

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.

1 Answer 1

4

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

unset($arr['val']);
$arr['val'] = $val;
Sign up to request clarification or add additional context in comments.

2 Comments

And how about, if i don't have the original $val ? Say i'm now in a different function and i only have access to $arr, and i want to remove all inner references.
@Kipras Then store the value, unset the array index, and reassign

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.