PHP: Clear/Delete/Remove operations on ArrayObject class

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);

=D 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/

Advertisement

2 Comments »

  1. Thank you for the article. ArrayObject is a good idea for itself but it should really be documented and extended with array manipulation methods.

  2. [...] PHP: Clear/Delete/Remove operations on ArrayObject class « Turboflash’s Blog [...]

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.