damijanc/collection

A simple PHP collection class to be used instead of ArrayObject

Maintainers

Package info

github.com/damijanc/collection

pkg:composer/damijanc/collection

Transparency log

Statistics

Installs: 9

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2018-10-09 13:52 UTC

This package is auto-updated.

Last update: 2026-08-17 07:32:03 UTC


README

A small PHP collection class for projects that need a simple object-oriented alternative to ArrayObject.

Collection implements ArrayAccess, IteratorAggregate, and Countable, so it can be used with array-access syntax, foreach, and count().

Installation

composer require damijanc/collection

Usage

use damijanc\Collection\Collection;

$collection = new Collection(['first' => 'value1']);

$collection[] = 'value2';
$collection['data'] = 'value3';

echo $collection['first'];
echo count($collection);

Collections can be initialized from any iterable. Keys are preserved:

$collection = new Collection([
    'first' => 'Ada',
    10 => 'Grace',
]);

You can iterate over the stored items:

foreach ($collection as $key => $item) {
    // Your logic here.
}

Use toArray() when you need the underlying array:

$items = $collection->toArray();

Missing Keys And Null Values

Reading a missing key throws OutOfBoundsException:

$collection = new Collection();

try {
    $collection['missing'];
} catch (\OutOfBoundsException $exception) {
    // Handle missing key.
}

Key existence checks use array_key_exists() semantics. A key with a null value is still considered present:

$collection = new Collection(['optional' => null]);

isset($collection['optional']); // true

Extending

The class is intentionally small and can be extended for domain-specific collections:

final class MyCollection extends Collection
{
    public function add(MyInterface $item): void
    {
        $this->collectionItems[] = $item;
    }
}

Requirements

PHP 8.0 or newer.