PHPackages                             galaxon/collections - 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. galaxon/collections

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

galaxon/collections
===================

Type-safe PHP collections: Sequence (ordered list), Dictionary (any-type keys), Set (unique values), with runtime type validation.

v1.0.1(1mo ago)15MITPHPPHP ^8.4

Since Dec 7Pushed 1mo agoCompare

[ Source](https://github.com/mossy2100/Galaxon-PHP-Collections)[ Packagist](https://packagist.org/packages/galaxon/collections)[ Docs](https://github.com/mossy2100/Galaxon-PHP-Collections)[ RSS](/packages/galaxon-collections/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (12)Versions (4)Used By (0)

Galaxon PHP Collections
=======================

[](#galaxon-php-collections)

Type-safe collection classes for PHP 8.4+.

**[License](LICENSE)** | **[Changelog](CHANGELOG.md)** | **[Documentation](docs/)**

[![PHP 8.4](docs/logo_php8_4.png)](docs/logo_php8_4.png)

---

Description
-----------

[](#description)

A type-safe collection library featuring runtime type validation, immutable operations, and unrestricted key types.

**Core Classes:**

- **Sequence** - Ordered lists with integer indexing
- **Dictionary** - Key-value pairs accepting any type as keys
- **Set** - Unique value collections with set operations

---

Development and Quality Assurance / AI Disclosure
-------------------------------------------------

[](#development-and-quality-assurance--ai-disclosure)

[Claude Chat](https://claude.ai) and [Claude Code](https://www.claude.com/product/claude-code) were used in the development of this package. The core classes were designed, coded, and commented primarily by the author, with Claude providing substantial assistance with code review, suggesting improvements, debugging, and generating tests and documentation. All code was thoroughly reviewed by the author, and validated using industry-standard tools including [PHP\_Codesniffer](https://github.com/PHPCSStandards/PHP_CodeSniffer/), [PHPStan](https://phpstan.org/) (to level 9), and [PHPUnit](https://phpunit.de/index.html) to ensure full compliance with [PSR-12](https://www.php-fig.org/psr/psr-12/) coding standards and comprehensive unit testing with 100% code coverage. This collaborative approach resulted in a high-quality, thoroughly-tested, and well-documented package delivered in significantly less time than traditional development methods.

[![Code Coverage](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)

---

Why Galaxon Collections?
------------------------

[](#why-galaxon-collections)

PHP's native arrays are powerful but have limitations:

- **Keys restricted to strings and integers** - Can't use booleans, floats, arrays, or objects as keys.
- **No type safety** - Arrays accept any mix of types without validation.
- **Type coercion issues** - Keys like `1`, `'1'`, `true`, and `1.0` all become the same key.
- **Limited operations** - Built-in array functions lack chaining, immutability, and advanced transformations. Errors and exceptions are inconsistent.

Galaxon Collections solves these problems with:

✅ **Any type as keys** - Use objects, arrays, booleans, floats, null as Dictionary keys.

✅ **Runtime type validation** - Optional type constraints with compile-time-like checking.

✅ **Rich API** - Fluent interfaces, method chaining, functional programming support.

✅ **Immutable operations** - Transformations return new collections without modifying originals.

✅ **Type inference** - Automatically detect types from your data.

✅ **Mathematical correctness** - Proper type safety for operations like sum() and product().

---

Alternatives
------------

[](#alternatives)

Before using this package, you may want to check out these PHP extensions:

- [Standard PHP Library](https://www.php.net/manual/en/book.spl.php)
- [Data Structures](https://www.php.net/manual/en/book.ds.php)

These are official PHP extensions that provide efficient data structure implementations and will probably be well-supported going forward. However, if you need runtime type safety and generics-like behavior, or simply prefer a more functional style of programming, Galaxon Collections provides features that these extensions lack, including type constraints, type inference, and type-safe operations.

---

Features
--------

[](#features)

### Type Safety

[](#type-safety)

```
// Restrict types at runtime
$numbers = new Sequence('int');
$numbers->append(1, 2, 3);    // ✅ Works
$numbers->append('four');      // ❌ InvalidArgumentException

// Union types
$mixed = new Sequence('int|string');
$mixed->append(1, 'two', 3);   // ✅ All work

// Type inference
$seq = new Sequence(source: [1, 2, 3]);
// Automatically infers type as 'int'
```

### Unrestricted Keys

[](#unrestricted-keys)

```
// PHP arrays: keys must be string|int
$array = [];
$array[new DateTime()] = 'event';  // ❌ Fatal error
$array[[1, 2]] = 'coords';         // ❌ Illegal offset

// Dictionary: any type works
$dict = new Dictionary();
$dict[new DateTime()] = 'event';         // ✅ Works
$dict[[1, 2, 3]] = 'coordinates';        // ✅ Works
$dict[fopen('file.txt', 'r')] = 'data';  // ✅ Works
$dict[true] = 'yes';                     // ✅ Works
$dict[null] = 'empty';                   // ✅ Works
```

### Functional Programming

[](#functional-programming)

```
$numbers = new Sequence('int', source: [1, 2, 3, 4, 5]);

// Method chaining
$result = $numbers
    ->filter(fn($n) => $n % 2 === 0)  // Keep evens
    ->map(fn($n) => $n * 2)            // Double them
    ->reverse();                       // Reverse order

echo $result; // [10, 8, 4]

// Original unchanged (immutable operations)
echo $numbers; // [1, 2, 3, 4, 5]
```

### Set Operations

[](#set-operations)

```
$set1 = new Set('int', [1, 2, 3, 4]);
$set2 = new Set('int', [3, 4, 5, 6]);

$union = $set1->union($set2);           // {1, 2, 3, 4, 5, 6}
$intersection = $set1->intersect($set2); // {3, 4}
$difference = $set1->diff($set2);        // {1, 2}

// Subset checking
$set1->subset($set2);      // false
$set1->disjoint($set2);  // false
```

---

Installation
------------

[](#installation)

```
composer require galaxon/collections
```

---

Requirements
------------

[](#requirements)

- PHP ^8.4
- galaxon/core

---

Quick Start
-----------

[](#quick-start)

### Sequence - Type-safe lists

[](#sequence---type-safe-lists)

```
use Galaxon\Collections\Sequence;

// Create with type inference
$seq = new Sequence(source: [1, 2, 3, 4, 5]);

// Add items
$seq->append(6, 7, 8);
$seq->prepend(0);

// Remove items
$item = $seq->removeByIndex(0);  // Returns removed value
$count = $seq->removeByValue(3); // Returns count removed

// Access items
echo $seq[0];        // 0
echo $seq->first();  // 0
echo $seq->last();   // 8

// Transformations
$evens = $seq->filter(fn($n) => $n % 2 === 0);
$doubled = $seq->map(fn($n) => $n * 2);
$sorted = $seq->sort();

// Aggregations
echo $seq->sum();      // 36
echo $seq->product();  // 0
echo $seq->average();  // 4.5
echo $seq->min();      // 0
echo $seq->max();      // 8
```

### Dictionary - Key-value pairs with any type

[](#dictionary---key-value-pairs-with-any-type)

```
use Galaxon\Collections\Dictionary;

// Create with type inference
$dict = new Dictionary(source: ['a' => 1, 'b' => 2]);

// Use objects as keys
$dict[new DateTime('2024-01-01')] = 'New Year';

// Use arrays as keys
$dict[[10, 20]] = 'coordinates';

// Type constraints
$typed = new Dictionary('string', 'int');
$typed['count'] = 42;      // ✅ Works
$typed['count'] = 'text';  // ❌ InvalidArgumentException

// Check and access
if ($dict->keyExists('a')) {
    echo $dict['a'];  // 1
}

// Iteration
foreach ($dict as $key => $value) {
    echo "$key => $value\n";
}
```

### Set - Unique values

[](#set---unique-values)

```
use Galaxon\Collections\Set;

// Duplicates automatically removed
$set = new Set(source: [1, 2, 2, 3, 3, 3]);
echo $set->count(); // 3

// Set operations
$a = new Set('int', [1, 2, 3]);
$b = new Set('int', [2, 3, 4]);

$a->union($b);       // {1, 2, 3, 4}
$a->intersect($b);   // {2, 3}
$a->diff($b);        // {1}

// Membership testing
var_dump($set->contains(2));  // true
var_dump($set->contains(5));  // false
```

---

Classes
-------

[](#classes)

### Core Collections

[](#core-collections)

- **[Collection](docs/Collection.md)** - Abstract base class providing shared functionality for all collection types
- **[Sequence](docs/Sequence.md)** - Ordered lists with integer indexing, similar to `List` in C# or Java
- **[Dictionary](docs/Dictionary.md)** - Key-value pairs accepting any PHP type for both keys and values
- **[Set](docs/Set.md)** - Unique value collections with mathematical set operations

### Supporting Classes

[](#supporting-classes)

- **[TypeSet](docs/TypeSet.md)** - Runtime type validation and constraint management
- **[Pair](docs/Pair.md)** - Immutable key-value pair container

---

Testing
-------

[](#testing)

The library includes comprehensive test coverage:

```
# Run all tests
vendor/bin/phpunit

# Run all tests for a specific collection type
vendor/bin/phpunit tests/Dictionary

# Run specific test class
vendor/bin/phpunit tests/Sequence/SequenceTransformationTest.php

# Run with coverage (generates HTML report and clover.xml)
composer test
```

**Test Coverage:**

- 500+ tests across all classes
- 100% code coverage
- Edge cases, error conditions, and type safety

---

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) for details

---

Support
-------

[](#support)

- **Issues**:
- **Documentation**: See [docs/](docs/) directory for detailed class documentation
- **Examples**: See test files for comprehensive usage examples

For questions or suggestions, please [open an issue](https://github.com/mossy2100/PHP-Collections/issues).

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history and changes.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance91

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~57 days

Total

3

Last Release

42d ago

Major Versions

v0.3.0 → v1.0.02026-01-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f9cd1bb5c1b12882db4cb82161c1b5a22e1ccbad8845a54a6ae591647e88c07?d=identicon)[mossy2100](/maintainers/mossy2100)

---

Top Contributors

[![mossy2100](https://avatars.githubusercontent.com/u/371497?v=4)](https://github.com/mossy2100 "mossy2100 (75 commits)")

---

Tags

phparraysetcollectionslistdictionarytype-safesequencetypedgenerics

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/galaxon-collections/health.svg)

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

###  Alternatives

[doctrine/collections

PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.

6.0k411.1M1.2k](/packages/doctrine-collections)[phpcollection/phpcollection

General-Purpose Collection Library for PHP

1.0k64.0M34](/packages/phpcollection-phpcollection)[equip/structure

Simple, immutable data structures

40201.9k2](/packages/equip-structure)[rotexsoft/versatile-collections

A collection package that can be extended to implement things such as a Dependency Injection Container, RecordSet objects for housing database records, a bag of http cookies, or technically any collection of items that can be looped over and whose items can each be accessed using array-access syntax or object property syntax.

186.0k1](/packages/rotexsoft-versatile-collections)

PHPackages © 2026

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