kuria / collections
Object-oriented collection structures
Requires
- php: >=7.1
- kuria/iterable: ^1.0
Requires (Dev)
- kuria/dev-meta: ^0.5
This package is auto-updated.
Last update: 2024-11-22 18:09:16 UTC
README
Object-oriented collection structures.
Contents
Features
Collection
- list of values with sequential integer indexesMap
- key-value map
Requirements
- PHP 7.1+
Collection
The Collection
class implements a list of values with sequential integer indexes.
It also implements Countable
, ArrayAccess
and IteratorAggregate
.
Creating a new collection
Empty collection
<?php use Kuria\Collections\Collection; $collection = Collection::create();
Using an existing iterable
<?php use Kuria\Collections\Collection; $collection = Collection::create(['foo', 'bar', 'baz']);
Using varargs
<?php use Kuria\Collections\Collection; $collection = Collection::collect('foo', 'bar', 'baz');
Collection method overview
Refer to doc comments of the respective methods for more information.
Static methods
create($values = null): self
- create a collection from an iterablecollect(...$values): self
- create a collection from the passed argumentsfill($value, $count): self
- create a collection and populate it with repeated valuesexplode($string, $delimiter, $limit = PHP_INT_MAX): self
- create a collection by splitting a string
Instance methods
setValues($values): void
- replace all values with the given iterabletoArray(): array
- get all values as an arrayisEmpty(): bool
- see if the collection is emptycount(): int
- count valueshas($index): bool
- see if the given index existscontains($value, $strict = true): bool
- see if the given value existsfind($value, $strict = true): ?int
- try to find the first occurence of a valueget($index): mixed
- get value at the given indexfirst(): mixed
- get first valuelast(): mixed
- get last valueindexes(): int[]
- get all indexesslice($index, $length = null): self
- extract a slice of the collectionreplace($index, $value): void
- replace a value at the given indexpush(...$values): void
- push one or more values onto the end of the collectionpop(): mixed
- pop a value off the end of the collectionunshift(...$values): void
- prepend one or more values to the beginning of the collectionshift(): mixed
- shift a value off the beginning of the collectioninsert($index, ...$values): void
- insert one or more values at the given indexpad($length, $value): void
- pad the collection with a value to the specified lengthremove(...$indexes): void
- remove values at the given indexesclear(): void
- remove all valuessplice($index, $length = null, $replacement = null): void
- remove or replace a part of the collectionsum(): int|float
- calculate the sum of all valuesproduct(): int|float
- calculate the product of all valuesimplode($delimiter = ''): string
- join all values using a delimiterreduce($callback, $initial = null): mixed
- reduce the collection to a single valuereverse(): self
- reverse the collectionchunk($size): self[]
- split the collection into chunks of the given sizesplit($number): self[]
- split the collection into the given number of chunksunique(): self
- get unique valuesshuffle(): self
- get values in random orderrandom($count): self
- get N random values from the collectioncolumn($key): self
- gather values from a property or array index of all object or array valuesmapColumn($valueKey, $indexKey): Map
- build a map using properties or array indexes of all object or array valuesfilter($filter): self
- filter values using the given callbackapply($callback): self
- apply the callback to all valuesmap($mapper): Map
- convert the collection to a mapmerge(...$iterables): self
- merge the collection with the given iterablesintersect(...$iterables): self
- compute an intersection with the given iterablesuintersect($comparator, ...$iterables): self
- compute an intersection with the given iterables using a custom comparatordiff(...$iterables): self
- compute a difference between this collection and the given iterablesudiff($comparator, ...$iterables): self
- compute a difference between this collection and the given iterables using a custom comparatorsort($flags = SORT_REGULAR, $reverse = false): self
- sort the collectionusort($comparator): self
- sort the collection using a custom comparator
Note
Any method that returns self
returns a new collection instance with the selected or modified values.
The original collection is not changed.
If updating the original collection is needed, use setValues()
to do so, e.g.:
<?php $collection->setValues($collection->sort());
Array access and iteration
Collection
instances can be accessed and iterated as regular arrays.
<?php use Kuria\Collections\Collection; $collection = Collection::create(); // push some values $collection[] = 'foo'; $collection[] = 'bar'; $collection[] = 'baz'; // replace a value $collection[1] = 'new bar'; // remove a value unset($collection[2]); // read values echo 'Value at index 1 is ', $collection[1], "\n"; echo 'Value at index 2 ', isset($collection[2]) ? 'exists' : 'does not exist', "\n"; // count values echo 'There are ', count($collection), ' values in total', "\n"; // iterate values foreach ($collection as $index => $value) { echo $index, ': ', $value, "\n"; }
Output:
Value at index 1 is new bar Value at index 2 does not exist There are 2 values in total 0: foo 1: new bar
Map
The Map
class implements a key value map.
It also implements Countable
, ArrayAccess
and IteratorAggregate
.
Creating a new map
Empty map
<?php use Kuria\Collections\Map; $map = Map::create();
Using an existing iterable
<?php use Kuria\Collections\Map; $map = Map::create(['foo' => 'bar', 'bar' => 'baz']);
Map method overview
Refer to doc comments of the respective methods for more information.
Static methods
create($pairs = null): self
- create a map from an iterablemap($iterable, $mapper): self
- map values of the given iterable using a callbackbuild($iterable, $mapper): self
- build a map from an iterable using a callbackcombine($keys, $values): self
- combine a list of keys and a list of values to create a map
Instance methods
setPairs($pairs): void
- replace all pairs with the given iterabletoArray(): array
- get all pairs as an arrayisEmpty(): bool
- see if the map is emptycount(): int
- count pairshas($key): bool
- see if the given key existscontains($value, $strict = true): bool
- see if the given value existsfind($value, $strict = true): string|int|null
- try to find the first occurence of a valueget($key): mixed
- get value for the given keyvalues(): Collection
- get all valueskeys(): Collection
- get all keysset($key, $value): void
- define a pairadd(...$iterables): void
- add pairs from other iterables to this mapfill($keys, $value): void
- fill specific keys with a valueremove(...$keys): void
- remove pairs with the given keysclear(): void
- remove all pairsreduce($reducer, $initial = null): mixed
- reduce the map to a single valueflip(): self
- swap keys and valuesshuffle(): self
- randomize pair ordercolumn($key, $indexBy = null): self
- gather values from properties or array keys of all object or array valuesfilter($filter): self
- filter pairs using the given callbackapply($callback): self
- apply the callback to all pairsmap($mapper): self
- remap pairs using the given callbackintersect(...$iterables): self
- compute an intersection with the given iterablesuintersect($comparator, ...$iterables): self
- compute an intersection with the given iterables using a custom comparatorintersectKeys(...$iterables): self
- compute a key intersection with the given iterablesuintersectKeys($comparator, ...$iterables): self
- compute a key intersection with the given iterables using a custom comparatordiff(...$iterables): self
- compute a difference between this map and the given iterablesudiff($comparator, ...$iterables): self
- compute a difference between this map and the given iterables using a custom comparatordiffKeys(...$iterables): self
- compute a key difference between this map and the given iterablesudiffKeys($comparator, ...$iterables): self
- compute a key difference between this map and the given iterables using a custom comparatorsort($flags = SORT_REGULAR, $reverse = false): self
- sort the map using its valuesusort($comparator): self
- sort the map using its values and a custom comparatorksort($flags = SORT_REGULAR, $reverse = false): self
- sort the map using its keysuksort(): self
- sort the map using its keys and a custom comparator
Note
Any method that returns self
returns a new map instance with the selected or modified pairs.
The original map is not changed.
If updating the original map is needed, use setPairs()
to do so, e.g.:
<?php $map->setPairs($map->sort());
Array access and iteration
Map
instances can be accessed and iterated as regular arrays.
<?php use Kuria\Collections\Map; $map = Map::create(); // add some pairs $map['foo'] = 'bar'; $map['baz'] = 'qux'; $map['quux'] = 'quuz'; // remove a pair unset($map['baz']); // read values echo 'Value with key "foo" is ', $map['foo'], "\n"; echo 'Value with key "baz" ', isset($map['baz']) ? 'exists' : 'does not exist', "\n"; // count pairs echo 'There are ', count($map), ' pairs in total', "\n"; // iterate pairs foreach ($map as $key => $value) { echo $key, ': ', $value, "\n"; }
Output:
Value with key "foo" is bar Value with key "baz" does not exist There are 2 pairs in total foo: bar quux: quuz