PHP Collection Class

by Andre Dubus March 12, 2026 Public
15 views Raw Download Revisions (v1)
Collection.php php Raw
<?php
class Collection implements Countable, IteratorAggregate {
    private array $items;

    public function __construct( array $items = [] ) {
        $this->items = array_values( $items );
    }

    public static function of( array $items ): static {
        return new static( $items );
    }

    public function map( callable $fn ): static {
        return new static( array_map( $fn, $this->items ) );
    }

    public function filter( callable $fn ): static {
        return new static( array_values( array_filter( $this->items, $fn ) ) );
    }

    public function each( callable $fn ): static {
        foreach ( $this->items as $item ) { $fn( $item ); }
        return $this;
    }

    public function first( ?callable $fn = null ) {
        if ( $fn ) return $this->filter( $fn )->first();
        return $this->items[0] ?? null;
    }

    public function reduce( callable $fn, mixed $carry = null ): mixed {
        return array_reduce( $this->items, $fn, $carry );
    }

    public function toArray(): array   { return $this->items; }
    public function count(): int       { return count( $this->items ); }
    public function isEmpty(): bool    { return empty( $this->items ); }
    public function getIterator(): ArrayIterator { return new ArrayIterator( $this->items ); }
}
Skip to toolbar