PHPackages                             omegaalfa/collection - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. omegaalfa/collection

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

omegaalfa/collection
====================

This library implements the Trie routing logic

v1.0.0(6mo ago)017[2 PRs](https://github.com/omegaalfa/collection/pulls)MITPHPPHP ^8.4CI passing

Since Jun 23Pushed 2mo agoCompare

[ Source](https://github.com/omegaalfa/collection)[ Packagist](https://packagist.org/packages/omegaalfa/collection)[ RSS](/packages/omegaalfa-collection/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (1)Dependencies (4)Versions (5)Used By (0)

🚀 PHP Collection Library
========================

[](#-php-collection-library)

[![PHP Version](https://camo.githubusercontent.com/f7278b6bf3029240c4a0d6658ca6de90405d58fa6f94ec323ac16db275089bd7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e332d3737374242343f7374796c653d666c61742d737175617265266c6f676f3d706870)](https://php.net/)[![License](https://camo.githubusercontent.com/422db9fd40f5831c765cf6530b6750c081b696bd18d904cf89554df98c676277/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e3f7374796c653d666c61742d737175617265)](LICENSE)[![Tests](https://camo.githubusercontent.com/3bf69bcc4b9d8076d0596fee68e644e78c88ddda90b31503baaf6ef0e6ab4d78/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3233392532307061737365642d737563636573733f7374796c653d666c61742d737175617265)](tests/)[![Coverage](https://camo.githubusercontent.com/1f2ab57f1e028421ef5a1d4504719d003398b46b3a4b308c5048f92dbd4483d6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d38302e38352532352d627269676874677265656e3f7374796c653d666c61742d737175617265)](coverage/)[![PHPStan](https://camo.githubusercontent.com/c62fc1b694a87f23eb42dabb9831151825700025b388074d0331f53520dcfdd5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230322d626c75653f7374796c653d666c61742d737175617265)](phpstan.neon)

**A powerful, type-safe PHP collection library with eager &amp; lazy evaluation** 🎯

[Features](#-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Documentation](#-documentation) • [Examples](#-examples)

---

✨ Features
----------

[](#-features)

### 🎯 **Type-Safe**

[](#-type-safe)

Full PHPDoc generics support

```
Sequence
Map
```

### ⚡ **Lazy Evaluation**

[](#-lazy-evaluation)

Memory-efficient processing

```
LazySequence::range(1, 1M)
  ->take(10) // Only 10 iterations!
```

### 🔒 **Immutable**

[](#-immutable)

Readonly data structures

```
$new = $seq->append(42);
// Original unchanged
```

- ✅ **7 Specialized Classes** - Collection, Sequence, Map, LazySequence, LazyMap, LazyFileIterator, LazyProxyObject
- ✅ **150+ Methods** - Rich API with fluent interface
- ✅ **Modern PHP** - PHP 8.3+ with strict types &amp; readonly properties
- ✅ **Well Tested** - 239 tests, 80.85% coverage
- ✅ **Zero Dependencies** - Pure PHP, no external packages required

📦 Installation
--------------

[](#-installation)

```
composer require omegaalfa/collection
```

### Requirements

[](#requirements)

RequirementVersionNote**PHP**`>= 8.3`Required**PHP**`>= 8.4`Recommended for `LazyProxyObject`---

🎯 Core Concepts
---------------

[](#-core-concepts)

ClassTypePurposeUse Case`Collection`**Generic**Iterator wrapper with transformations✅ Mixed data, legacy code, Iterator support`Sequence`**Eager**Ordered immutable list✅ Small lists, type safety, immutability`Map`**Eager**Immutable key-value dictionary✅ Small maps, type safety, immutability`LazySequence`**Lazy**Generator-based pipeline✅ Large datasets, streaming, memory efficiency`LazyMap`**Lazy**Lazy value computation✅ Expensive computations, caching, DI`LazyFileIterator`**Lazy**File streaming (JSON lines)✅ Large files, memory constraints`LazyProxyObject`**Lazy**PHP 8.4+ lazy object instantiation✅ Expensive objects, service containers---

� Quick Start
-------------

[](#-quick-start)

### 💡 Collection - Generic Wrapper

[](#-collection---generic-wrapper)

**Click to expand**```
use Omegaalfa\Collection\Collection;

// Create from array or Iterator
$collection = new Collection([1, 2, 3, 4, 5]);

// Transform (eager)
$doubled = $collection->map(fn($x) => $x * 2);
$evens = $collection->filter(fn($x) => $x % 2 === 0);

// 🚀 Lazy methods (memory efficient!)
$result = Collection::lazyRange(1, 1000000)
    ->lazyMap(fn($x) => $x * 2)
    ->lazyFilter(fn($x) => $x > 100)
    ->lazyTake(10);  // Only processes ~51 elements!

// Array access
$collection['key'] = 'value';
echo $collection['key'];

// Statistics
echo $collection->sum();    // 15
echo $collection->avg();    // 3
echo $collection->count();  // 5
```

### 📋 Sequence - Ordered Immutable List

[](#-sequence---ordered-immutable-list)

**Click to expand**```
use Omegaalfa\Collection\Sequence;

// Create
$numbers = Sequence::of(1, 2, 3, 4, 5);
$range = Sequence::range(1, 10);

// Immutable transformations
$doubled = $numbers->map(fn($x) => $x * 2);
$evens = $numbers->filter(fn($x) => $x % 2 === 0);

// 🔗 Fluent chaining
$result = Sequence::range(1, 100)
    ->filter(fn($x) => $x % 3 === 0)
    ->map(fn($x) => $x * $x)
    ->take(5);

// Access
echo $numbers->at(0);      // 1
echo $numbers->first();    // 1
echo $numbers->last();     // 5

// Operations (returns new Sequence)
$appended = $numbers->append(6);
$prepended = $numbers->prepend(0);
$inserted = $numbers->insert(2, 99);
$removed = $numbers->remove(2);
```

### 🗺️ Map - Immutable Key-Value Dictionary

[](#️-map---immutable-key-value-dictionary)

**Click to expand**```
use Omegaalfa\Collection\Map;

// Create
$user = Map::of(
    'name', 'John',
    'age', 30,
    'city', 'NY'
);

// Access
echo $user->get('name');               // John
echo $user->getOrDefault('email', '-'); // -

// Transform (returns new Map)
$aged = $user->put('age', 31);
$removed = $user->remove('city');

// 🔄 Transformations
$uppercased = $user->mapValues(fn($k, $v) => is_string($v) ? strtoupper($v) : $v);
$prefixed = $user->mapKeys(fn($k) => "user_$k");

// Merge
$merged = $user->merge(Map::of('email', 'john@example.com'));
```

### ⚡ LazySequence - Generator-Based Pipeline

[](#-lazysequence---generator-based-pipeline)

**Click to expand**```
use Omegaalfa\Collection\LazySequence;

// 🚀 Pipeline - NOTHING executes until iteration!
$pipeline = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);

// Now it executes - only ~51 iterations!
foreach ($pipeline as $value) {
    echo $value;  // 102, 104, 106...
}

// ⚡ Short-circuit operations
$first = LazySequence::range(1, 1000000)->first();  // Stops at 1

// Materialize to eager
$eager = $lazy->toEager();  // Returns Sequence
```

### 🎯 LazyMap - Lazy Value Computation

[](#-lazymap---lazy-value-computation)

**Click to expand**```
use Omegaalfa\Collection\LazyMap;

// Values are closures - computed on-demand! 💡
$config = LazyMap::from([
    'database' => fn() => new Database(),  // Not created yet
    'cache' => fn() => new Redis(),        // Not created yet
    'api' => fn() => new ApiClient()       // Not created yet
]);

// ⚡ Only creates Database when accessed
$db = $config->get('database');

// 🆕 With LazyProxyObject (PHP 8.4+)
$services = LazyMap::ofLazyObjects([
    'logger' => [Logger::class, $config],
    'mailer' => [Mailer::class, $smtp]
]);

// Creates lazy proxy - object instantiated on first method call
$logger = $services->get('logger');
$logger->info('message');  // NOW Logger is instantiated
```

### 📁 LazyFileIterator - Stream Large Files

[](#-lazyfileiterator---stream-large-files)

**Click to expand**```
use Omegaalfa\Collection\LazyFileIterator;

// 📄 Stream JSON lines file (memory efficient!)
$iterator = new LazyFileIterator('data.jsonl');

foreach ($iterator as $index => $object) {
    echo "Line {$index}: {$object->name}\n";
}

// Use with Collection for transformations
$collection = new Collection($iterator);
$filtered = $collection->lazyFilter(fn($obj) => $obj->active);
```

---

🎯 Choosing the Right Class
--------------------------

[](#-choosing-the-right-class)

### Use **Collection** 💡

[](#use-collection-)

- ✅ Working with `Iterator` instances
- ✅ Need array-like access (`ArrayAccess`)
- ✅ Want both eager and lazy methods
- ✅ Migrating legacy code

### Use **Sequence** 📋

[](#use-sequence-)

- ✅ Need ordered list (0-indexed)
- ✅ Want immutability
- ✅ Working with small-to-medium datasets
- ✅ Type safety is important

### Use **Map** 🗺️

[](#use-map-️)

- ✅ Need key-value pairs
- ✅ Want immutability
- ✅ Working with configuration, dictionaries
- ✅ Type safety is important

### Use **LazySequence** ⚡

[](#use-lazysequence-)

- ✅ Large datasets (millions of items)
- ✅ Memory is constrained
- ✅ Need pipeline composition
- ✅ Can benefit from short-circuit evaluation

### Use **LazyMap** 🎯

[](#use-lazymap-)

- ✅ Values are expensive to compute
- ✅ Not all values will be accessed
- ✅ Need lazy initialization
- ✅ Dependency injection containers

### Use **LazyFileIterator** 📁

[](#use-lazyfileiterator-)

- ✅ Processing large JSON line files
- ✅ Cannot load entire file in memory
- ✅ Streaming data processing

---

� API Reference
---------------

[](#-api-reference)

**🔥 Core Methods - Quick Reference**### 🔄 Transformation

[](#-transformation)

```
map(callable $fn): self           // Transform each element
filter(callable $fn): self        // Keep matching elements
flatMap(callable $fn): self       // Map + flatten
reduce(callable $fn, mixed $init) // Reduce to single value
```

### 📊 Aggregation

[](#-aggregation)

```
sum(): int|float                  // Sum all numeric values
avg(): int|float                  // Calculate average
min(): mixed                      // Find minimum
max(): mixed                      // Find maximum
count(): int                      // Count elements
```

### 🔍 Retrieval

[](#-retrieval)

```
first(): mixed                    // Get first element
last(): mixed                     // Get last element
find(callable $fn): mixed         // Find matching element
any(callable $fn): bool           // Check if any matches
all(callable $fn): bool           // Check if all match
```

### ⚡ Lazy Operations

[](#-lazy-operations)

```
take(int $n): self               // Take first n elements
skip(int $n): self               // Skip first n elements
chunk(int $size): self           // Split into chunks
takeWhile(callable $fn): self    // Take while predicate true
skipWhile(callable $fn): self    // Skip while predicate true
```

**📋 Full Method Compatibility Matrix**MethodCollectionSequenceMapLazySequenceLazyMap`map`✅✅✅✅✅`filter`✅✅✅✅✅`reduce`✅✅✅✅✅`take`✅✅✅✅✅`skip`✅✅✅✅✅`chunk`✅✅✅✅✅`sort`✅✅❌✅❌`reverse`✅✅❌✅❌`unique`✅✅❌✅❌`merge`✅✅✅✅✅`keys`✅❌✅❌✅`values`✅✅✅✅✅`mapKeys`❌❌✅❌✅`mapValues`❌❌✅❌✅> 📖 **Complete documentation:** [docs/API.md](docs/API.md) • **150+ methods documented**

---

⚡ Performance &amp; Optimization
--------------------------------

[](#-performance--optimization)

### 💾 Memory Efficiency

[](#-memory-efficiency)

#### Traditional Approach ❌

[](#traditional-approach-)

```
// Processes 1M elements
$data = range(1, 1000000);
$result = array_map(
    fn($x) => $x * 2,
    array_filter($data, fn($x) => $x % 2 === 0)
);
```

**Result:** ~400 MB | ~850ms

#### Lazy Evaluation ✅

[](#lazy-evaluation-)

```
// Only processes 51 elements!
$result = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);
```

**Result:** ~2 MB | ~0.7ms
🚀 **2290x FASTER!**

### 📊 Benchmark Results

[](#-benchmark-results)

**View Detailed Benchmarks**```
📊 Processing 1,000,000 items:

Traditional Array:        ~400 MB peak | ~850ms
Collection (eager):       ~380 MB peak | ~820ms
LazySequence:            ~2 MB peak   | ~12ms   ⚡ 70x faster
LazyFileIterator:        ~1 MB peak   | ~8ms    ⚡ 106x faster

```

**Operation:** `map → filter → take(100)`

ImplementationTimeMemoryvs ArrayArray850ms400 MBbaselineCollection820ms380 MB1.04x fasterLazySequence12ms2 MB**70x faster**LazyFileIterator8ms1 MB**106x faster**### 🎯 Lazy vs Eager Trade-offs

[](#-lazy-vs-eager-trade-offs)

ScenarioUse Lazy ⚡Use Eager 🏃Large datasets (100k+)✅ Memory efficient❌ High memoryExpensive operations✅ Deferred execution❌ Upfront costShort-circuit (`take`, `first`)✅ Early termination❌ Full processingMultiple transformations✅ Single-pass❌ Multiple passesSmall datasets (&lt;1k)❌ Overhead✅ FastRandom access❌ Must materialize✅ Direct access> 🔍 **Detailed analysis:** [docs/PROFILING\_ANALYSIS.md](docs/PROFILING_ANALYSIS.md)

---

🧪 Testing
---------

[](#-testing)

```
# Run all tests
composer test

# Run with coverage report
composer test:coverage

# Static analysis (PHPStan level 9)
composer phpstan
```

### 📊 Code Quality Metrics

[](#-code-quality-metrics)

MetricValueStatus**Tests**239 tests✅**Assertions**374 assertions✅**Line Coverage**80.85%✅**Method Coverage**76.92%✅**PHPStan Level**Max (9)✅

---

📖 Documentation
---------------

[](#-documentation)

### 📘 Core Documentation

[](#-core-documentation)

- [Complete API Reference](docs/API.md)
- [LazyFileIterator Guide](docs/LazyFileIterator_README.md)
- [Performance Profiling](docs/PROFILING_ANALYSIS.md)

### 💡 Examples &amp; Guides

[](#-examples--guides)

- [Complete Usage Examples](examples/COMPLETE_USAGE_EXAMPLES.php)
- [Examples Directory](examples/)
- [Changelog](CHANGELOG.md)

---

🏆 Benchmark
-----------

[](#-benchmark)

Run the included benchmark script:

```
php benchmark.php
```

**Sample Output**```
🎯 Collection Library Benchmark
================================

📊 Test: map + filter + take(100) on 1,000,000 items

✅ Traditional Array:     850ms  |  400 MB
✅ Collection (eager):    820ms  |  380 MB
✅ LazySequence:          12ms   |  2 MB    🚀 70x faster
✅ LazyFileIterator:      8ms    |  1 MB    🚀 106x faster

💡 Winner: LazyFileIterator
   - 106x faster
   - 400x less memory
   - Perfect for streaming large datasets

```

---

🏗️ Architecture
---------------

[](#️-architecture)

**📐 Class Hierarchy &amp; Design Patterns**```
Contract/
├── MapInterface           # Contract for Map implementations
└── SequenceInterface      # Contract for Sequence implementations

Traits/
├── CollectionTransformationsTrait  # Transformation operations
├── CollectionAggregatesTrait       # Aggregation operations
├── CollectionArrayAccessTrait      # ArrayAccess implementation
└── LazyOperationsTrait             # Lazy evaluation operations

Core Classes/
├── Collection             # Hybrid: Eager + Lazy operations
├── Sequence              # Immutable ordered list
├── Map                   # Immutable key-value map
├── LazySequence          # Generator-based lazy sequence
└── LazyMap               # Lazy-evaluated map (Closures)

Utilities/
├── LazyProxyObject       # PHP 8.4+ lazy object proxies
└── LazyFileIterator      # Stream large files efficiently

File Parsers/
├── ParserInterface
├── JsonLinesParser       # Parse .jsonl files
├── CsvParser             # Parse CSV files
├── TsvParser             # Parse TSV files
└── PlainTextParser       # Parse plain text

```

### 🎨 Design Principles

[](#-design-principles)

#### ✅ Core Principles

[](#-core-principles)

- **Immutability:** All transformations return new instances
- **Lazy Evaluation:** Defer computation until needed
- **Type Safety:** Full PHPDoc generics support
- **Interface Contracts:** Clear API boundaries

#### 🌟 Inspired By

[](#-inspired-by)

- [Never Use Arrays (Larry Garfield)](https://www.garfieldtech.com/blog/never-use-arrays)
- Scala/Kotlin Collections
- Java Streams API
- Rust Iterators

---

📄 License
---------

[](#-license)

This project is licensed under the **MIT License**
See the [LICENSE](LICENSE) file for details

```
Permission is hereby granted, free of charge, to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software.

```

---

🤝 Contributing
--------------

[](#-contributing)

**Contributions are welcome!** 🎉

### 📝 How to Contribute

[](#-how-to-contribute)

1. 🍴 **Fork** the repository
2. 🌿 **Create** a feature branch ```
    git checkout -b feature/amazing-feature
    ```
3. ✅ **Ensure** all tests pass ```
    composer test
    composer phpstan
    ```
4. 📝 **Commit** your changes ```
    git commit -m 'feat: add amazing feature'
    ```
5. 📤 **Push** to the branch ```
    git push origin feature/amazing-feature
    ```
6. 🎉 **Open** a Pull Request

### 📋 Contribution Guidelines

[](#-contribution-guidelines)

RequirementDescription✅ **Tests**All tests must pass (`composer test`)✅ **PHPStan**Level 9 compliance required✅ **Coverage**Maintain &gt;75% code coverage✅ **PSR-12**Follow PHP coding standards✅ **Conventional Commits**Use semantic commit messages---

💬 Support &amp; Community
-------------------------

[](#-support--community)

ChannelLinkDescription🐛 **Issues**[GitHub Issues](https://github.com/omegaalfa/collection/issues)Bug reports &amp; feature requests💡 **Discussions**[GitHub Discussions](https://github.com/omegaalfa/collection/discussions)Questions &amp; ideas📧 **Email**Direct support📖 **Docs**[Documentation](docs/)Complete guides

---

### ⭐ Star History

[](#-star-history)

[![Star History Chart](https://camo.githubusercontent.com/f3cab29c4a5a1de8e480d342f8733152a1bb92edf350e2a221a23da4f8c3a68f/68747470733a2f2f6170692e737461722d686973746f72792e636f6d2f7376673f7265706f733d6f6d656761616c66612f636f6c6c656374696f6e26747970653d44617465)](https://star-history.com/#omegaalfa/collection&Date)

---

**Made with ❤️ by the Omegaalfa Team**

⭐ **Star this repo** if you find it useful!

[📖 Documentation](docs/) • [💡 Examples](examples/) • [📝 Changelog](CHANGELOG.md) • [📄 License](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance80

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 75.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~557 days

Total

2

Last Release

183d ago

Major Versions

v0.0.1 → v1.0.02026-01-01

PHP version history (2 changes)v0.0.1PHP &gt;=8.1

v1.0.0PHP ^8.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16062691?v=4)[omegaalfa](/maintainers/omegaalfa)[@omegaalfa](https://github.com/omegaalfa)

---

Top Contributors

[![omegaalfa](https://avatars.githubusercontent.com/u/16062691?v=4)](https://github.com/omegaalfa "omegaalfa (22 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")

---

Tags

arraymemorycollectionperfomance

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/omegaalfa-collection/health.svg)

```
[![Health](https://phpackages.com/badges/omegaalfa-collection/health.svg)](https://phpackages.com/packages/omegaalfa-collection)
```

###  Alternatives

[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.3k459.4k15](/packages/aimeos-map)[athari/yalinqo

YaLinqo, a LINQ-to-objects library for PHP

4581.2M5](/packages/athari-yalinqo)[yansongda/supports

common components

211.4M32](/packages/yansongda-supports)[armincms/json

A Laravel Nova field.

26156.7k3](/packages/armincms-json)[graze/data-structure

Data collections and containers

12295.9k10](/packages/graze-data-structure)[graze/sort

A collection of array sorting transforms and functions

11298.3k2](/packages/graze-sort)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
