PHP collection class

This is a simple PHP class to manage a collection of items.

Refer to the sample at the end for usage example.

Collection.php:
<?php
class Collection {
    var $elements = array();
    var $counter = 0;
    var $pointer = 0;

    function Collection() {

    }

    function add($element) {
        $this->elements[$this->counter] = $element;
        $this->counter++;
        $this->pointer++;
    }

    function remove($element) {
        $found = null;
        for ($i = 0; $i < count($this->elements); $i++) {
            if ($this->elements[$i] == $element) {
                $found = $i;
            }
        }
        if ($found != null) {
            array_splice($this->elements, $found, 1);
            $this->counter--;
            $this->pointer--;
        }
    }

    function contains($element) {
        for ($i = 0; $i < count($this->elements); $i++) {
            if ($this->elements[$i] == $element) {
                return true;
            }
        }
        return false;
    }

    function hasNext() {
        return $this->pointer < $this->counter;
    }

    function hasPrevious() {
        return $this->pointer > 0;
    }

    function next() {
        return $this->elements[$this->pointer++];
    }

    function first() {
        $this->pointer = 0;
        return $this->elements[$this->pointer];
    }

    function last() {
        $this->pointer = $this->counter;
        return $this->elements[$this->pointer];
    }

    function previous() {
        return $this->elements[--$this->pointer];
    }

    function count() {
        return count($this->elements);
    }
}
?>
Example usage:
<?php
require_once "Collection.php";

$collection = new Collection();

for ($i = 0; $i < 10; $i++) {
    $element = "Element $i";
    $collection->add($element);
}

$collection->first();
while ($collection->hasNext() ) {
    $element = $collection->next();
    echo $element . "n";
}

echo "n";

$collection->previous();
$collection->previous();
$collection->remove("Element 7");

$collection->last();
while ($collection->hasPrevious() ) {
    $element = $collection->previous();
    echo $element . "n";
}

?>

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.