jast99 / sorted-linked-list
SortedLinkedList
v1.0.0
2026-03-20 13:24 UTC
Requires
- php: ^8.2
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^11.0
- squizlabs/php_codesniffer: ^3.0
README
A PHP library providing a sorted linked list that keeps values in order. It can hold int or string values, but not both at the same time.
Requires PHP 8.2+.
Installation
composer require jast99/sorted-linked-list
Usage
Creating a list
use JaSt99\SortedLinkedList\SortedLinkedList; $integers = SortedLinkedList::ofIntegers(); $strings = SortedLinkedList::ofStrings();
Inserting values
Values are automatically inserted in sorted order:
$list = SortedLinkedList::ofIntegers(); $list->insert(5); $list->insert(1); $list->insert(3); $list->toArray(); // [1, 3, 5]
Removing values
Returns true if the value was found and removed, false otherwise. If duplicates exist, only the first occurrence is removed.
$list->remove(3); // true $list->remove(99); // false
Checking for values
$list->contains(5); // true $list->contains(99); // false
Accessing first and last element
$list->first(); // smallest value $list->last(); // largest value
Both methods throw EmptyListException when the list is empty.
Count and emptiness
$list->count(); // number of elements $list->isEmpty(); // true if empty count($list); // works too (Countable interface)
Iteration
The list implements IteratorAggregate, so you can use foreach:
foreach ($list as $value) { echo $value . PHP_EOL; }
Converting to array and string
$list->toArray(); // [1, 3, 5] $list->toString(); // '1, 3, 5' $list->toString(';'); // '1;3;5' $list->toString(' | '); // '1 | 3 | 5'
Custom comparator
By default, values are sorted using PHP's native <=> operator. You can provide a custom comparator:
// Case-insensitive string sorting $list = SortedLinkedList::ofStrings(strcasecmp(...)); $list->insert('Banana'); $list->insert('apple'); $list->toArray(); // ['apple', 'Banana'] // Reverse integer sorting $list = SortedLinkedList::ofIntegers(fn(int $a, int $b): int => $b <=> $a); $list->insert(1); $list->insert(3); $list->toArray(); // [3, 1]
Type safety
The list enforces type consistency both at static analysis level (PHPStan generics) and at runtime:
$list = SortedLinkedList::ofIntegers(); $list->insert('foo'); // throws ListTypeMismatchException
Development
# Run tests vendor/bin/phpunit # Run static analysis vendor/bin/phpstan analyse # Check coding standard vendor/bin/phpcs
License
MIT