Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsetting referenced array items

Tags:

arrays

php

$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)

like image 208
Alex Avatar asked Aug 28 '26 06:08

Alex


1 Answers

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]);
like image 149
Mike Dinescu Avatar answered Aug 29 '26 19:08

Mike Dinescu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!