Collection is a set of useful wrapper classes for arrays, similar to Java's or Kotlin's collection packages.
Since Version 4.0 you need PHP 7.4 or higher to use this library. Since Version 2.1 you need PHP 7.1 to use Collection library. Previous versions are running from PHP 5.6 upwards.
The recommended way to install Collection is through Composer.
# Install Composer
curl -sS https://getcomposer.org/installer | phpNext, run the Composer command to install the latest stable version of Collection:
php composer.phar require seboettg/collectionAfter installing, you need to require Composer's autoloader:
require'vendor/autoload.php';You can then later update Collection using composer:
composer.phar updateList is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. In other words: a list can contain any number of equal objects or occurrences of a single object. Two lists are considered equal if they have the same sizes and structurally equal elements at the same positions.
Lists are completely new implemented for version 4.0. The handling is much more oriented on a functional approach. Further more methods for associative arrays are moved to map.
usefunctionSeboettg\Collection\Lists\listOf;
usefunctionSeboettg\Collection\Lists\listFromArray;
//create a simple list$list = listOf("a", "b", "c", "d");
print_r($list);Output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => a
[1] => b
[2] => c
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
You also create a list from an existing array
$array = ["d", "e", "f"];
$otherList = listFromArray($array);Output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => d
[1] => e
[2] => f
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
As you may notice, this will reset the array keys
You can also create an empty List:
usefunctionSeboettg\Collection\Lists\emptyList;
$emptyList = emptyList();
echo$emptyList->count();output
0
foreach ($listas$key => $value) {
echo"[".$key."] => ".$value."\n";
}Output:
[0] => a
[1] => b
[2] => c
or
for ($i = 0; $i < $otherList->count(); ++$i) {
echo$otherList->get($i) . "";
}output
d e f
You may add the elements of another list to a list by using plus:
$newList = $list->plus($otherList);
print_r($newList);output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
The same operation is applicable with arrays, with the same result:
$newList = $list->plus($array);You can also subtract the elements of another list or any iterable using minus:
$subtract = $newList->minus($list);
print_r($subtract);output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => d
[1] => e
[2] => f
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
To get the intersection of two lists (or an iterable), you can use the intersect method:
$intersection = $newList->intersect(listOf("b", "d", "f", "h", "i"));
print_r($intersection);output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => b
[1] => d
[2] => f
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
To get a list containing distinct elements, use distinct:
$list = listOf("a", "b", "a", "d", "e", "e", "g")
print_r($list->distinct());output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => a
[1] => b
[2] => d
[3] => e
[4] => g
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
If you need to modify all elements in a list, you can do it easily by using the map method:
$list = listOf(1, 2, 3, 4, 5);
$cubicList = $list->map(fn ($i) => $i * $i * $i);
//result of $cubicList: 1, 8, 27, 64, 125There is also a mapNotNull method that eliminates null values from the result:
functiondivisibleByTwoOrNull(int$number): ?int {
return$item % 2 === 0 ? $item : null;
}
listOf(0, 1, 2, 3, 4, 5)
->map(fn (int$number): ?int => divisibleByTwoOrNull($number));
//result: 0, 2, 4The filter method returns a list containing only elements matching the given predicate.
$list = listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"):
$listOfCharactersThatAsciiNumbersIsOdd = $list
->filter(fn($letter) => ord($letter) % 2 !== 0);
//result of $listOfCharactersTharOrderNumbersAreOdd: "a", "c", "e", "g", "i"With the methods any and all you can check whether all elements (all) or at least one element (any) match a predicate.
$list = listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"):
$list->all(fn($letter) => ord($letter) % 2 !== 0); // false$list->any(fn($letter) => ord($letter) % 2 !== 0); // true$list->all(fn($letter) => ord($letter) % 1 !== 0); // true$list->any(fn($letter) => $letter === "z"); // false, since no character in the list is a 'z'With the forEach method you can apply a closure or lambda functions on each element.
$list = listOf("a", "b", "c");
$list->forEach(fn (string$item) => print($item . PHP_EOL));output:
a
b
c
Implement the Comparable interface
<?phpnamespaceVendor\App\Model;
useSeboettg\Collection\Comparable\Comparable;
class Element implements Comparable
{
private$attribute1;
private$attribute2;
//contructorpublicfunction__construct($attribute1, $attribute2)
{
$this->attribute1 = $attribute1;
$this->attribute2 = $attribute2;
}
// getterpublicfunctiongetAttribute1() { return$this->attribute1; }
publicfunctiongetAttribute2() { return$this->attribute2; }
//compareTo functionpublicfunctioncompareTo(Comparable$b): int
{
returnstrcmp($this->attribute1, $b->getAttribute1());
}
}Create a comparator class
<?phpnamespaceVendor\App\Util;
useSeboettg\Collection\Comparable\Comparator;
useSeboettg\Collection\Comparable\Comparable;
class Attribute1Comparator extends Comparator
{
publicfunctioncompare(Comparable$a, Comparable$b): int
{
if ($this->sortingOrder === Comparator::ORDER_ASC) {
return$a->compareTo($b);
}
return$b->compareTo($a);
}
}Sort your list
<?phpuseSeboettg\Collection\Lists;
useSeboettg\Collection\Collections;
useSeboettg\Collection\Comparable\Comparator;
usefunctionSeboettg\Collection\Lists\listOf;
useVendor\App\Util\Attribute1Comparator;
useVendor\App\Model\Element;
$list = listOf(
newElement("b","bar"),
newElement("a","foo"),
newElement("c","foobar")
);
Collections::sort($list, newAttribute1Comparator(Comparator::ORDER_ASC));<?phpuseSeboettg\Collection\Comparable\Comparator;
useSeboettg\Collection\Comparable\Comparable;
useSeboettg\Collection\Lists;
useSeboettg\Collection\Collections;
usefunctionSeboettg\Collection\Lists\listOf;
useVendor\App\Model\Element;
//Define a custom Comparatorclass MyCustomOrderComparator extends Comparator
{
publicfunctioncompare(Comparable$a, Comparable$b): int
{
return (array_search($a->getAttribute1(), $this->customOrder) >= array_search($b->getAttribute1(), $this->customOrder)) ? 1 : -1;
}
}
$list = listOf(
newElement("a", "aa"),
newElement("b", "bb"),
newElement("c", "cc"),
newElement("k", "kk"),
newElement("d", "dd"),
);
Collections::sort(
$list, newMyCustomOrderComparator(Comparator::ORDER_CUSTOM, ["d", "k", "a", "b", "c"])
);A Map stores key-value pairs; keys are unique, but different keys can be paired with equal values. The Map interface provides specific methods, such as access to value by key, searching keys and values, and so on.
A Map is a collection of keys that are paired with values. Therefore, to create a Map you need pairs first:
useSeboettg\Collection\Map\Pair;
usefunctionSeboettg\Collection\Map\pair;
usefunctionSeboettg\Collection\Map\mapOf;
$pair1 = pair("Ceres", "Giuseppe Piazzi")
//or you use the factory, with the same result:$pair2 = Pair::factory("Pallas", "Heinrich Wilhelm Olbers");
//Now you can add both pairs to a map$map = mapOf($pair1, $pair2);
print_r($map);output
Seboettg\Collection\Map\MapInterface@anonymous Object
(
[array:Seboettg\Collection\Map\MapInterface@anonymous:private] => Array
(
[Ceres] => Giuseppe Piazzi
[Pallas] => Heinrich Wilhelm Olbers
)
)
You can also create an empty Map:
usefunctionSeboettg\Collection\Map\emptyMap;
$emptyMap = emptyMap();
echo$emptyMap->count();output
0
usefunctionSeboettg\Collection\Map\mapOf;
$asteroidExplorerMap = mapOf(
pair("Ceres", "Giuseppe Piazzi"),
pair("Pallas", "Heinrich Wilhelm Olbers"),
pair("Juno", "Karl Ludwig Harding"),
pair("Vesta", "Heinrich Wilhelm Olbers")
);
$juno = $asteroidExplorerMap->get("Juno"); //Karl Ludwig Harding// or access elements like an array$pallas = $asteroidExplorerMap["Pallas"]; //Heinrich Wilhelm Olbers//get a list of all keys$asteroids = $asteroidExplorerMap->getKeys(); //Ceres, Pallas, Juno, Vesta//get a list of all values$explorer = $asteroidExplorerMap
->values()
->distinct(); // "Giuseppe Piazzi", "Heinrich Wilhelm Olbers", "Karl Ludwig Harding"$explorer = $asteroidExplorerMap
->getOrElse("Iris", fn() => "unknown"); //$explorer = "unknown"you are also able to get all map entries as a list of pairs
$keyValuePairs = $asteroidExplorerMap->getEntries();output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => Seboettg\Collection\Map\Pair Object
(
[key:Seboettg\Collection\Map\Pair:private] => Ceres
[value:Seboettg\Collection\Map\Pair:private] => Giuseppe Piazzi
)
[1] => Seboettg\Collection\Map\Pair Object
(
[key:Seboettg\Collection\Map\Pair:private] => Pallas
[value:Seboettg\Collection\Map\Pair:private] => Heinrich Wilhelm Olbers
)
[2] => Seboettg\Collection\Map\Pair Object
(
[key:Seboettg\Collection\Map\Pair:private] => Juno
[value:Seboettg\Collection\Map\Pair:private] => Karl Ludwig Harding
)
[3] => Seboettg\Collection\Map\Pair Object
(
[key:Seboettg\Collection\Map\Pair:private] => Vesta
[value:Seboettg\Collection\Map\Pair:private] => Heinrich Wilhelm Olbers
)
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
usefunctionSeboettg\Collection\Map\emptyMap;
$map = emptyMap();
//put$map->put("ABC", 1);
echo$map["ABC"]; // 1//put via array assignment$map["ABC"] = 2;
echo$map["ABC"]; // 2//remove$map->put("DEF", 3);
$map->remove("DEF");
echo$map->get("DEF"); // nullThe signature of given transform function for mapping must have either a Pair parameter or a key and a value parameter.
The map function always returns a list of type ListInterface:
usefunctionSeboettg\Collection\Map\mapOf;
class Asteroid {
publicstring$name;
public ?string$explorer;
public ?float$diameter;
publicfunction__construct(string$name, string$explorer, float$diameter = null)
{
$this->name = $name;
$this->explorer = $explorer;
$this->diameter = $diameter;
}
}
$asteroids = $asteroidExplorerMap
->map(fn (Pair$pair): Asteroid => newAsteroid($pair->getKey(), $pair->getValue()));
print_r($asteroids);output
Seboettg\Collection\Lists\ListInterface@anonymous Object
(
[array:Seboettg\Collection\Lists\ListInterface@anonymous:private] => Array
(
[0] => Asteroid Object
(
[name] => Ceres
[explorer] => Giuseppe Piazzi
[diameter] => )
[1] => Asteroid Object
(
[name] => Pallas
[explorer] => Heinrich Wilhelm Olbers
[diameter] => )
[2] => Asteroid Object
(
[name] => Juno
[explorer] => Karl Ludwig Harding
[diameter] => )
[3] => Asteroid Object
(
[name] => Vesta
[explorer] => Heinrich Wilhelm Olbers
[diameter] => )
)
[offset:Seboettg\Collection\Lists\ListInterface@anonymous:private] => 0
)
You get the same result with a key-value signature:
$asteroids = $asteroidExplorerMap
->map(fn (string$key, string$value): Asteroid => newAsteroid($key, $value));You may filter for elements by this way:
$asteroidExplorerMap->filter(fn (Pair$pair): bool => $pair->getKey() !== "Juno");or by this way:
$asteroidExplorerMap->filter(fn (string$key, string$value): bool => $key !== "Juno");There are a lot of opportunities to use lists and maps in real world scenarios with a lot of advantages e.g. less boilerplate code and better code readability.
The following json file represents a customer file that we want to use for processing.
customer.json
[
{
"id": "A001",
"lastname": "Doe",
"firstname": "John",
"createDate": "2022-06-10 09:21:12"
},
{
"id": "A002",
"lastname": "Doe",
"firstname": "Jane",
"createDate": "2022-06-10 09:21:13"
},
{
"id": "A004",
"lastname": "Mustermann",
"firstname": "Erika",
"createDate": "2022-06-11 08:21:13"
}
]We would like to get a map that associates the customer id with respective objects of type Customer and we want to apply a filter
so that we get only customers with lastname Doe.
usefunctionSeboettg\Collection\Lists\listFromArray;
class Customer {
publicstring$id;
publicstring$lastname;
publicstring$firstname;
publicDateTime$createDate;
publicfunction__construct(
string$id,
string$lastname,
string$firstname,
DateTime$createDate
) {
$this->id = $id;
$this->lastname = $lastname;
$this->firstname = $firstname;
$this->createDate = $createDate;
}
}
$customerList = listFromArray(json_decode(file_get_contents("customer.json"), true));
$customerMap = $customerList
->filter(fn (array$customerArray) => $customerArray["lastname"] === "Doe") // filter for lastname Doe
->map(fn (array$customerArray) => newCustomer(
$customerArray["id"],
$customerArray["lastname"],
$customerArray["firstname"],
DateTime::createFromFormat("Y-m-d H:i:s", $customerArray["createDate"])
)) // map array to customer object
->associateBy(fn(Customer$customer) => $customer->id); // link the id with the respective customer objectprint_($customerMap);output
Seboettg\Collection\Map\MapInterface@anonymous Object
(
[array:Seboettg\Collection\Map\MapInterface@anonymous:private] => Array
(
[A001] => Customer Object
(
[id] => A001
[lastname] => Doe
[firstname] => John
[createDate] => DateTime Object
(
[date] => 2022-06-10 09:21:12.000000
[timezone_type] => 3
[timezone] => UTC
)
)
[A002] => Customer Object
(
[id] => A002
[lastname] => Doe
[firstname] => Jane
[createDate] => DateTime Object
(
[date] => 2022-06-10 09:21:13.000000
[timezone_type] => 3
[timezone] => UTC
)
)
)
)
Another example: Assuming we have a customer service with a getCustomerById method.
We have a list of IDs with which we want to request the service.
$listOfIds = listOf("A001", "A002", "A004");
$customerMap = $listOfIds
->associateWith(fn ($customerId) => $customerService->getById($customerId))output
Seboettg\Collection\Map\MapInterface@anonymous Object
(
[array:Seboettg\Collection\Map\MapInterface@anonymous:private] => Array
(
[A001] => Customer Object
(
[id] => A001
[lastname] => Doe
[firstname] => John
[createDate] => DateTime Object
(
[date] => 2022-06-10 09:21:12.000000
[timezone_type] => 3
[timezone] => UTC
)
)
[A002] ...
[A004] ...
)
)
A stack is a collection of elements, with two principal operations:
- push, which adds an element to the collection, and
- pop, which removes the most recently added element that was not yet removed.
An Stack is a LIFO data structure: last in, first out.
$stack = newStack();
$stack->push("a")
->push("b")
->push("c");
echo$stack->pop(); // outputs cecho$stack->count(); // outputs 2// peek returns the element at the top of this stack without removing it from the stack.echo$stack->peek(); // outputs becho$stack->count(); // outputs 2The search function returns the position where an element is on this stack. If the passed element occurs as an element in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost element on the stack is considered to be at distance 1. If the passed element does not occur in the stack, this method returns 0.
echo$stack->search("c"); //outputs 0 since c does not exist anymoreecho$stack->search("a"); //outputs 2echo$stack->search("b"); //outputs 1A queue is a collection in which the elements are kept in order. A queue has two principle operations:
- enqueue
- dequeue
$queue = newQueue();
$queue->enqueue("d")
->enqueue("z")
->enqueue("b")
->enqueue("a");
echo$queue->dequeue(); // outputs decho$queue->dequeue(); // outputs zecho$queue->dequeue(); // outputs becho$queue->count(); // outputs 1Fork this Repo and feel free to contribute your ideas using pull requests.


