I want to clear all elements from an array object (which can be a standard PHP array, an ArrayObject or basically any other object that implements the basic array interfaces such as Itertable, ArrayAccess, Countable etc.). However, I do not want to reinstate the object, so I somehow have to unset all the individual elements, instead of creating a new object of the same type. Is there an easy way to do this?
-
4Why don't you want to reinstate an object/array?Crozin– Crozin2011-02-01 12:36:06 +00:00Commented Feb 1, 2011 at 12:36
-
Because the object is a function parameter, and I do not necessarily have knowledge of where it comes from or how to instantiate it.mrjames– mrjames2011-02-01 12:56:33 +00:00Commented Feb 1, 2011 at 12:56
7 Answers
foreach ($array as $key => $element) {
unset($array[$key]);
}
This requires both Traversable and ArrayAccess, Countable is not required. Or obviously just a normal array.
2 Comments
exchangeArray, but arrayiterator doesn't have something like this.I'm not entirely sure why you need to do it this way, but in answer to your question, you should be able to simply use the array_splice function to remove all of the objects from your array;
$my_array = array('A', 'B', 'C');
array_splice($my_array, 0);
I've never used array_splice to remove all objects from an array, but I assume it works in the same manner.
1 Comment
In case you remove the last record from array than the next foreach loop can fail (internaly calling $this->next() )
So it helped me to test the validy and break in this case the next loop.
deleteOffset = true;
foreach ($iterator as $key => $value)
{
if ($deleteOffset && $iterator->offsetExists($key) )
{
$iterator->offsetUnset($key);
}
//if remove last record than the foreach ( $this->next() ) fails so
//we have to break in this case the next ->next call
if (!$iterator->valid()) break;
}