1

I have always deleted objects from an array with unset():

unset($arr['theKey']);

... thereby assuming that if no other references where held to the object in $arr['theKey'] the garbage collector would delete the object.

I took over a legacy application, and here all objects are deleted that way:

$arr['theKey'] = null;
unset($arr['theKey']);

Is setting the element to null necessary?

lukas.j
  • 6,453
  • 2
  • 5
  • 24
  • 1
    Does this answer your question? [the difference between unset and = null](https://stackoverflow.com/a/50931077) – Blackhole Jan 17 '22 at 19:57
  • You have the `key`, so you dont need anything else. Assign the object key to `null` is an unnecessary and useless work.Because anyway you will unset the `key` and after that, the `key` is not exist, so it is not important than before `unset` you assiلد the `key` to `null` , and is a extra and useless work – Milad pegah Jan 17 '22 at 20:06
  • @Blackhole: My question is not about _unset_ vs _null_. I am trying to understand what the reason could be why both statements were used. – lukas.j Jan 17 '22 at 20:06
  • 2
    @lukas.j It's explained in the answer I linked: `null` "frees" the memory immediately, whereas `unset` just mark it for garbage collection. So the only reason you may want both is to free the memory immediately AND remove the key from the array. But honestly, I don't there is ever a good reason not to just `unset` it. – Blackhole Jan 17 '22 at 20:13

0 Answers0