Eelco Luurtsema
Eelco Luurtsema

Reputation: 1199

Unset passed by reference, also unsets original value

I want a reference to an array, and then unset the reference to a few elements of the array. For the question, I have simplified the code:

echo"1:";
print_r($this->data);
$return =& $this->data;
foreach(range(1,10) AS $key)
{
    unset($return[$key]);
}
echo"2:";
print_r($this->data);

$this->data is an array. This code should keep $this->data untouched, but it doesn't. The output is:

1:Array
(
[0] => Array
    (
        [id] => 1
    )

[1] => Array
    (
        [id] => 2
    )

[2] => Array
    (
        [id] => 3
    )

[3] => Array
    (
        [id] => 4
    )

[4] => Array
    (
        [id] => 5
    )

[5] => Array
    (
        [id] => 6
    )

[6] => Array
    (
        [id] => 7
    )

[7] => Array
    (
        [id] => 8
    )

[8] => Array
    (
        [id] => 9
    )

[9] => Array
    (
        [id] => 10
    )

)
2:Array
(
[0] => Array
    (
        [id] => 1
    )

)

Why is by unsetting the reference, the array in $this->data being changed? All other questions at stackoverflow concerning deleting references uses the unset() function, so why is this giving problems?

Thanks.

Upvotes: 0

Views: 236

Answers (2)

TecBrat
TecBrat

Reputation: 3729

The difference is that you are not actually unsetting the reference. You are unsetting a value within the referenced data. See this sandbox: PHP Unset Test

$a=1;
$b = & $a;

unset($a);
echo 'B'."\n";
echo $b;

echo "\n\n";

$c=array(0,1,2,3);
$d = & $c;

unset($c);

echo 'D'."\n";
var_export($d);

echo "\n\n";

$e=array(0,1,2,3);
$f = & $e;

unset($f[2]);
echo 'E'."\n";
var_export($e);

Output:

B
1

D
array (
  0 => 0,
  1 => 1,
  2 => 2,
  3 => 3,
)

E
array (
  0 => 0,
  1 => 1,
  3 => 3,
)

Upvotes: 0

Oswald
Oswald

Reputation: 31685

By creating a reference using $return =& $this->data, you are basically giving the array $this->data a new name. That's what references are. Now it does not make any difference whether you access the array using the new name or the old name.

Upvotes: 1

Related Questions