php-standard-library/collection
Object-oriented Vector, Map, and Set collections for PHP with both immutable and mutable variants. Part of PHP Standard Library, focused on generic, reusable data structures with consistent APIs. Docs and contribution links available at php-standard-library.dev.
Installation:
composer require php-standard-library/collection
No additional configuration is required—just autoload the package.
First Use Case:
use PhpStandardLibrary\Collection\Vector;
use PhpStandardLibrary\Collection\Map;
// Immutable Vector (fixed-size, ordered)
$immutableVector = Vector::of(1, 2, 3);
// Mutable Map (key-value, dynamic)
$mutableMap = new Map();
$mutableMap->put('name', 'John');
$mutableMap->put('age', 30);
Where to Look First:
Vector, Map, and Set classes in the PhpStandardLibrary\Collection namespace.Vector<int>) for compile-time checks.Data Transformation:
$numbers = Vector::of(1, 2, 3);
$doubled = $numbers->map(fn($n) => $n * 2); // Immutable
$mutableDoubled = $numbers->toMutable()->map(fn($n) => $n * 2); // Mutable
Filtering and Reduction:
$evenNumbers = $numbers->filter(fn($n) => $n % 2 === 0);
$sum = $numbers->reduce(0, fn($acc, $n) => $acc + $n);
Nested Collections:
$nestedMap = new Map();
$nestedMap->put('users', Vector::of(
Map::of('id' => 1, 'name' => 'Alice'),
Map::of('id' => 2, 'name' => 'Bob')
));
Interoperability with Laravel:
// Convert Laravel Collection to/from package collections
$laravelColl = collect([1, 2, 3]);
$packageVector = Vector::fromArray($laravelColl->toArray());
$this->app->bind(Vector::class, fn() => Vector::empty());
Map::of() or Vector::of() with objects for structured data:
$user = Map::of(
'id' => 1,
'roles' => Vector::of('admin', 'user')
);
Vector for ordered, indexed data (O(1) access) and Map for key-value lookups (O(log n) for immutable, O(1) for mutable).Immutable vs Mutable Confusion:
map(), filter()).toMutable()->put()).toImmutable()/toMutable().Type Inference Limits:
Vector<int> with Vector<string> in the same context.@var annotations or IDE hints for complex cases.Lazy Evaluation:
filter()) return lazy iterators. Force evaluation with toArray() or reduce() if needed.Laravel Collection Overlap:
Collection with this package’s collections in the same pipeline (e.g., laravelColl->merge($packageMap) may fail).$packageMap = Map::fromArray($laravelColl->toArray());
$map->inspect(); // Dumps the entire structure (useful for debugging)
isImmutable() to verify collection type before operations.$isEven = fn($n) => $n % 2 === 0;
$numbers->filter($isEven);
JsonSerializable for custom objects stored in Map/Vector:
class User implements JsonSerializable {
public function jsonSerialize() { ... }
}
$map->put('user', new User());
toMutable()->putAll()) over immutable chains.How can I help you explore Laravel packages today?