r/PHPhelp • u/brianlovely • Jun 21 '25
Solved Removing element from array that is the property of an object
I have an object that has an array as one of its properties. I need to be able to permanently remove elements from that array within one of the object's methods. Within the function, it seems like $this->someArray is now missing the element, but it doesn't seem to be actually gone from the object's array, if you see what I mean.
I've tried unset, splice, and slice, but none seem to permanently remove the element.
How can I remove an element from an array that is the property of an object?
3
Upvotes
4
u/allen_jb Jun 21 '25
There should be no difference removing elements from an array that's a property than one that's a normal variable.
Can you provide a script that reproduces the issue. I would suggest using https://3v4l.org or another sandbox.
2
u/liamsorsby Jun 21 '25
Do you have an example? Have you stepped through the code using something like xdebug?
0
u/LordAmras Jun 21 '25 edited Jun 22 '25
Unset should work, the thing in php is that when you remove an element of array it doesn't rearrange the values so if you have:
$array = [0=> 'a', 1=> 'b', 2=> 'c' ] and you do unset($array[1]) it would become [0=> 'a', 2=> 'c' ]
You can reorder the keys with array_values($array) that will return [0=> 'a', 1=> 'c' ]
Edit: removed reference to null in the 1 index