3
$arr = array('a' => 1, 'b' => 2);

$xxx = &$arr['a'];

unset($xxx);

print_r($arr);  // still there :(

so unset only breaks the reference...

Do you know a way to unset the element in the referenced array?

Yes, I know I could just use unset($arr['a']) in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't.

This question is kind of related to this one (this is the reason why that solution doesn't work)

1
  • Cant you unset($arr); ?? Commented Feb 5, 2012 at 2:34

3 Answers 3

2

I may be wrong but I think the only way to unset the element in the array would be to look up the index that matches the value referenced by the variable you have, then unsetting that element.

 $arr = array('a' => 1, 'b' => 2);
 $xxx = &$arr['a'];

 $keyToUnset = null;
 foreach($arr as $key => $value)
 {
      if($value === $xxx)
      {
          $keyToUnset = $key;
          break;
      }
 }
 if($keyToUnset !== null)
     unset($arr[$keyToUnset]);
 $unset($xxx);

Well, anyway, something along those lines. However, keep in mind that this is not super efficient because each time you need to unset an element you have to iterate over the full array looking for it.

Assuming you have control over how $xxx is used, you may want to consider using it to hold the key in the array, instead of a reference to the element at the key. That way you wouldn't need to search the array when you wanted to unset the element. But you would have to replace all sites that use $xxx with an array dereference:

$arr = array('a' => 1, 'b' => 2);
$xxx = 'a';

// instead of $xxx, use:
$arr[$xxx];

// to unset, simply
unset($arr[$xxx]);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, but what about the following code? $arr = array('a' => 1, 'b' => 2, 'c'=>1); $xxx = &$arr['c']; That's why it doesn't work for me :(
1

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed.

And with respect to the code above - I do not think there is need in separate key

foreach($arr as $key => $value)
{
      if($value === $xxx)
      {
          unset($arr[$key]);
          break;
      }
 }

Comments

0

The simple answer:

$arr = array('a' => 1, 'b' => 2);

$xxx = 'a';

unset($arr[$xxx]);

print_r($arr);  // gone :)

i.e.. You probably don't ever really need a reference. Just set $xxx to the appropriate key.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.