🗂️

PHP Data Structures

A zero-dependency PHP library providing 6 typed data structures with 60+ methods: Stack, Queue, Collection, Set, TypedArray, and Pair.

PHP Data Structures · v1.0.0 · 0 downloads

Download

curl -OL https://ahmedhabib.com/libraries/download/php-data-structures
6
Classes
60+
Methods
0
Dependencies
8.0+
PHP Version
require_once 'PhpDataStructures.php';

Stack (LIFO)

9 methods for last-in-first-out operations with push, pop, peek, and iteration

Stack::push / pop / peek
Push items onto the top, pop from the top, or peek without removing.
$stack = new Stack();
$stack->push('a', 'b', 'c');

$stack->peek();  // "c" (top item)
$stack->pop();   // "c" (removed)
$stack->pop();   // "b"
$stack->size();  // 1
Stack::from / contains / isEmpty
Create from array, check for values, and test emptiness.
$stack = Stack::from([1, 2, 3]);

$stack->contains(2);  // true
$stack->isEmpty();     // false
$stack->size();        // 3

$stack->clear();
$stack->isEmpty();     // true
Stack — Iteration & Counting
Implements Countable and IteratorAggregate. Iterates top-to-bottom.
$stack = Stack::from(['x', 'y', 'z']);

count($stack); // 3

foreach ($stack as $item) {
    echo $item; // z, y, x (top-first)
}

Queue (FIFO)

10 methods for first-in-first-out operations with enqueue, dequeue, and peek

Queue::enqueue / dequeue
Add to the back, remove from the front — classic FIFO behavior.
$q = new Queue();
$q->enqueue('first', 'second', 'third');

$q->dequeue(); // "first"
$q->dequeue(); // "second"
$q->size();    // 1
Queue::front / back
Peek at the front or back item without removing it.
$q = Queue::from(['a', 'b', 'c']);

$q->front(); // "a"
$q->back();  // "c"
Queue::from / contains / clear
Create from array, check membership, and clear the queue.
$q = Queue::from([10, 20, 30]);

$q->contains(20); // true
$q->isEmpty();     // false

$q->clear();
$q->isEmpty();     // true

Collection (Fluent Array Wrapper)

25 chainable methods for transforming, filtering, aggregating, and slicing data

Collection::of / map / filter
Create a collection and chain transformations fluently.
$result = Collection::of([1, 2, 3, 4, 5])
    ->filter(fn($n) => $n > 2)
    ->map(fn($n) => $n * 10)
    ->toArray();
// [30, 40, 50]
Collection::reduce / sum / avg / min / max
Aggregate values with reduce, sum, average, min, and max.
$c = Collection::of([10, 20, 30]);

$c->sum();  // 60
$c->avg();  // 20
$c->min();  // 10
$c->max();  // 30

$c->reduce(fn($carry, $n) => $carry + $n, 0);
// 60
Collection::first / last
Get the first or last item, optionally matching a condition.
$users = Collection::of([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob',   'age' => 30],
    ['name' => 'Carol', 'age' => 35],
]);

$users->first(); // ["name"=>"Alice", ...]
$users->first(fn($u) => $u['age'] > 28);
// ["name"=>"Bob", "age"=>30]
Collection::pluck / groupBy
Extract a single column or group items by a shared key.
$items = Collection::of([
    ['type' => 'fruit', 'name' => 'Apple'],
    ['type' => 'veg',   'name' => 'Carrot'],
]);

$items->pluck('name')->toArray();
// ["Apple", "Carrot"]

$items->groupBy('type');
// ["fruit" => Collection, "veg" => Collection]
Collection::sort / reverse / unique / chunk
Sort, reverse, deduplicate, or split into chunks — all chainable.
Collection::of([3, 1, 2, 1])
    ->unique()   // [3, 1, 2]
    ->sort()     // [1, 2, 3]
    ->reverse()  // [3, 2, 1]
    ->chunk(2);  // [[3,2], [1]]
Collection::take / skip / slice / merge
Take the first N, skip N, slice a range, or merge collections.
$c = Collection::of(['a', 'b', 'c', 'd', 'e']);

$c->take(3)->toArray();  // ["a","b","c"]
$c->skip(2)->toArray();  // ["c","d","e"]

$c->merge(['f', 'g'])->toArray();
// ["a","b","c","d","e","f","g"]
Collection::toJson / toArray / each
Convert to JSON, plain array, or iterate with side effects.
$c = Collection::of([1, 2, 3]);

$c->toJson();  // "[1,2,3]"
$c->toArray(); // [1, 2, 3]

$c->each(function($item, $key) {
    echo "{$key}: {$item}\n";
});

Set (Unique Values)

12 methods for unique-value collections with union, intersect, and diff operations

Set::add / remove / has
Add values (duplicates ignored), remove values, and check membership.
$set = new Set();
$set->add('php')->add('js')->add('php');

$set->size();         // 2 (no duplicates)
$set->has('php');      // true

$set->remove('js');
$set->toArray();      // ["php"]
Set::union / intersect / diff
Mathematical set operations — all return new Set instances.
$a = new Set([1, 2, 3]);
$b = new Set([2, 3, 4]);

$a->union($b)->toArray();
// [1, 2, 3, 4]

$a->intersect($b)->toArray();
// [2, 3]

$a->diff($b)->toArray();
// [1]
Set::isSubsetOf / from / clear
Check subset relationship, create from varargs, and clear all values.
$small = new Set([1, 2]);
$big   = new Set([1, 2, 3, 4]);

$small->isSubsetOf($big); // true
$big->isSubsetOf($small); // false

$tags = Set::from('php', 'mysql', 'redis');
$tags->size(); // 3

TypedArray (Type-Enforced Array)

10 methods for type-safe arrays that enforce a single type for all elements

TypedArray::of / add / get / set
Create a typed array and add/access elements. Throws on type mismatch.
$ids = TypedArray::of('int', 1, 2, 3);

$ids->add(4);       // OK
$ids->get(0);       // 1
$ids->set(0, 10);   // replace index 0

$ids->add('five');   // InvalidArgumentException!
// "Expected type [int], got [string]."
TypedArray — Class Types
Enforce object types using fully-qualified class names.
$users = new TypedArray(User::class);

$users->add(new User('Alice')); // OK
$users->add(new User('Bob'));   // OK
$users->add('not a user');     // throws!

$users->getType(); // "User"
TypedArray — Array Access
Supports bracket syntax via ArrayAccess, plus Countable and iteration.
$names = TypedArray::of('string', 'a', 'b');

$names[] = 'c';       // append via []
$names[0] = 'x';      // overwrite index 0
count($names);         // 3

foreach ($names as $name) {
    echo $name;        // x, b, c
}

Pair (Immutable Key-Value Tuple)

9 methods for immutable key-value pairs with equality checks and conversions

Pair::of / key / value
Create an immutable pair and access its key and value.
$pair = Pair::of('name', 'Alice');

$pair->key();    // "name"
$pair->value();  // "Alice"
Pair::withKey / withValue
Create a new Pair with a modified key or value (original unchanged).
$original = Pair::of('color', 'blue');

$updated = $original->withValue('red');
$original->value(); // "blue" (unchanged)
$updated->value();  // "red"
Pair::toArray / toAssoc / equals / from
Convert to arrays, compare pairs, or create from an existing array.
$p = Pair::of('lang', 'PHP');

$p->toArray(); // ["lang", "PHP"]
$p->toAssoc(); // ["lang" => "PHP"]

$p2 = Pair::from(['lang', 'PHP']);
$p->equals($p2); // true

json_encode($p);
// {"key":"lang","value":"PHP"}

About This Library

PHP Data Structures is a single-file, zero-dependency library for PHP 8.0+ that provides essential data structures missing from native PHP. Includes a LIFO Stack, FIFO Queue, fluent chainable Collection, unique-value Set, type-enforced TypedArray, and immutable key-value Pair. Every class is fully typed, implements Countable and IteratorAggregate where appropriate, and follows modern PHP conventions. Drop it into any project and start using it immediately.

How to Use

  1. Download PhpDataStructures.php
  2. Include or autoload it in your project
  3. Use the data structure classes: Stack, Queue, Collection, Set, TypedArray, Pair
ESC