Random Access interfaces

ArrayAccess interface

ArrayAccess interface allows random access to your collection through the array index operator []:

ArrayAccess {
     /* Methods */
     abstract public boolean offsetExists ( mixed $offset )
     abstract public mixed offsetGet ( mixed $offset )
     abstract public void offsetSet ( mixed $offset , mixed $value )
     abstract public void offsetUnset ( mixed $offset )

Example of Book class that implements ArrayAccess

class Book implements ArrayAccess {
    public $title;

    public $author;

    public $isbn;

    public function offsetExists( $offset )
        return isset( $this->$offset );

    public function offsetSet( $offset, $value)
        $this->$offset = $value;

    public function offsetGet( $offset )
        return $this->$offset;

    public function offsetUnset( $offset )
        unset( $this->$offset );
} /*** end of class ***/

$book = new book;

$book['title']= 'Pro PHP';
$book['author'] = 'Kevin McArthur';
$book['isbn'] = 1590598199;

foreach($book as $key => $value) {
    echo "<p>book[$key] = $value</p>\n";

Note: In PHP any class can be used in a foreach loop—provided it has public properties. It does not have to implement the Iterator interface(or one that extends it). By default the public properties of the object are returned by default. ArrayAccess does not provided foreach iterability rather the fact that Book is a class.

As mentioned earlier, ArrayObject implements not only ArrayAccess but also Countable, Serializeable and IteratorAggregate. Extending it has the added convenvience of these additional interfaces, in addition to the methods specific to ArrayObject such as append and various sorting methods, like sort, natsort, uasort, and uksort. See ArrayObject_.