There wasn’t much information available on the Internet by keyword searching on how to do clearing/deleting/removing operations on PHP ArrayObject class so I decided to contribute a small post on this topic and hopefully it will save some time for people researching on it.

As of 7 February 2009, the PHP: ArrayObject – Manual did not document two very important methods in the class: exchangeArray() and getArrayCopy(). So I do agree with some post I came across that ArrayObject in not very well documented and the methods should be included there.

Sunstorm Labs Blog has actually written a very interesting article on the topic of ArrayObject so you might like to read it up. Some foundation here is actually based on that article and we will just concentrate on the operations mentioned in the title.

exchangeArray() and getArrayCopy() methods

You can’t really apply array functions directly on the ArrayObject instance. In order to use them, you need to do it as follows.

$arrayObject = new ArrayObject(array(1, 2, 3));
$array = $arrayObject->getArrayCopy();
$array = array_function($array);
$arrayObject->exchangeArray($array);

Clearing ArrayObject

This can be done using the following line. Simple and straight forward, isn’t it? 🙂

$arrayObject->exchangeArray(array());

Deleting/Removing value from ArrayObject

This is where the exchangeArray() and getArrayCopy() methods come into action. We will apply array_splice function for the deleting/removal action.

$arrayObject = new ArrayObject(array(1, 2, 3));
$array = $arrayObject->getArrayCopy();
array_splice($array, . . .);
$arrayObject->exchangeArray($array);

If there is any better way of doing this, remember to share them with me.

Excellent References:
http://www.php.net/manual/en/class.arrayobject.php
http://www.php.net/~helly/php/ext/spl/classArrayObject.html
http://www.php.net/manual/en/book.array.php
http://www.sunstormlabs.net/blog/2008/02/29/what-good-are-arrayobjects/