Collection provides a powerful data manipulation system based on the map/reduce/filter principles. Thanks to the php generators and the immutability, it allows to calculate the data as late as possible while preserving the memory.
composer require camillebaronnet/collection
public Collection::__construct(...$elements)
public Collection::__construct(\Traversable|array $elements)
Exemple :
$collection = (new Collection('foo', 'bar'))
->map(fn($word) => 'hello '.$word)
->map(fn($word) => strtoupper($word))
;
// The data is computed only here
var_dump($collection->toArray());
array(2) {
[0]=>
string(9) "HELLO FOO"
[1]=>
string(9) "HELLO BAR"
}
- map(callable): Collection
- filter(callable): Collection
- reduce(callable, initial): mixed
- flatten(): Collection
- flatMap(callable): Collection
- sort(callable = null): Collection
- sum(): int|float
- avg(): int|float
- unique(): Collection
- count(): int
- first(): mixed
- each(): Collection
- groupBy(callable): CollectionGroup
Note : As long as you use map/filter operations, nothing will be executed or stored
in memory. If you decide to do more than one reduce or iterate operation, use get()
first to before to buffer the previous operations.
The map()
function iterates over each element and applies the transformation function provided by the user.
map(fn($element) => /* ... */);
Example :
(new Collection(10, 50, 100))
->map(fn($element) => $element * 2)
->toArray()
;
// [20, 100, 200]
The filter()
method test elements using that pass the test implemented by the provided function.
filter(fn ($element) => /* ... */);
Example :
(new Collection(10, 50, 100))
->filter(fn($element) => $element > 20)
->toArray()
;
// [50, 100]
The reduce()
method executes a reduction function provided by the user on each element, the result of each iteration is passed to the next iteration.
reduce(fn($carry, $currentValue, $currentKey) => /* ... */, $initial);
Example :
(new Collection(10, 50, 100))
->reduce(fn($carry, $current) => $carry + $current)
;
// 160
The method groupBy()
returns a Collection of CollectionGroup.
A CollectionGroup is a simple collection with a key
property added.
groupBy(fn ($element) => /* ... */);
Example :
$result = (new Collection([
['key1' => 'foo', 'key2' => 10],
['key1' => 'bar', 'key2' => 11],
['key1' => 'foo', 'key2' => 12],
['key1' => 'bar', 'key2' => 14],
]))
->groupBy(fn($x) => $x['key1'])
->toArray() // [CollectionGroup, CollectionGroup]
;
$result[0]->key; // 'foo'
$result[0]->toArray(); // [['key1' => 'foo', 'key2' => 10],['key1' => 'foo', 'key2' => 12],]