开发者

Emptying a PHP array

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 objec开发者_运维知识库t of the same type. Is there an easy way to do this?


foreach ($array as $key => $element) {
    unset($array[$key]);
}

This requires both Traversable and ArrayAccess, Countable is not required. Or obviously just a normal array.


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.


I am having trouble deciphering what the question is really asking for. Replacing the array/iterator with an empty iterator (an EmptyIterator, or another iterator with no values?) might suffice.

$array = new EmptyIterator;


Try

$my_array = array('A', 'B', 'C');
unset($my_array);


What about a simple unset?

unset($array);


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;

    }


The best place PHP Manual

http://php.net/manual/en/function.unset.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜