CollectionInterface
extends
Iterator, JsonSerializable
in
Describes the methods a Collection should implement. A collection is an immutable list of elements exposing a number of traversing and extracting method for generating other collections.
Table of Contents
Methods
- append() : self
- Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
- appendItem() : self
- Append a single item creating a new collection.
- avg() : float|int|null
- Returns the average of all the values extracted with $path or of this collection.
- buffered() : self
- Returns a new collection where the operations performed by this collection.
- cartesianProduct() : self
- Create a new collection that is the cartesian product of the current collection
- chunk() : self
- Breaks the collection into smaller arrays of the given size.
- chunkWithKeys() : self
- Breaks the collection into smaller arrays of the given size.
- combine() : self
- Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
- compile() : self
- Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result.
- contains() : bool
- Returns true if $value is present in this collection. Comparisons are made both by value and type.
- count() : int
- Returns the amount of elements in the collection.
- countBy() : self
- Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
- countKeys() : int
- Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
- each() : $this
- Applies a callback to the elements in this collection.
- every() : bool
- Returns true if all values in this collection pass the truth test provided in the callback.
- extract() : self
- Returns a new collection containing the column or property value found in each of the elements.
- filter() : self
- Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
- first() : mixed
- Returns the first result in this collection
- firstMatch() : mixed
- Returns the first result matching all the key-value pairs listed in conditions.
- groupBy() : self
- Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
- indexBy() : self
- Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item.
- insert() : self
- Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
- isEmpty() : bool
- Returns whether there are elements in this collection
- jsonSerialize() : array<string|int, mixed>
- Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
- last() : mixed
- Returns the last result in this collection
- lazy() : self
- Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yielded one at a time.
- listNested() : self
- Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
- map() : self
- Returns another collection after modifying each of the values in this one using the provided callable.
- match() : self
- Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
- max() : mixed
- Returns the top element in this collection after being sorted by a property.
- median() : float|int|null
- Returns the median of all the values extracted with $path or of this collection.
- min() : mixed
- Returns the bottom element in this collection after being sorted by a property.
- nest() : self
- Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
- prepend() : self
- Prepend a set of items to a collection creating a new collection
- prependItem() : self
- Prepend a single item creating a new collection.
- reduce() : mixed
- Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function.
- reject() : self
- Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
- sample() : self
- Returns a new collection with maximum $length random elements from this collection
- shuffle() : self
- Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
- skip() : self
- Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
- some() : bool
- Returns true if any of the values in this collection pass the truth test provided in the callback.
- sortBy() : self
- Returns a sorted iterator out of the elements in this collection, ranked based on the results of applying a callback function to each value.
- stopWhen() : self
- Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
- sumOf() : float|int
- Returns the total sum of all the values extracted with $matcher or of this collection.
- take() : self
- Returns a new collection with maximum $length elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
- takeLast() : self
- Returns the last N elements of a collection
- through() : self
- Passes this collection through a callable as its first argument.
- toArray() : array<string|int, mixed>
- Returns an array representation of the results
- toList() : array<string|int, mixed>
- Returns an numerically-indexed array representation of the results.
- transpose() : self
- Transpose rows and columns into columns and rows
- unfold() : self
- Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
- unwrap() : Traversable
- Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
- zip() : self
- Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
- zipWith() : self
- Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Methods
append()
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
public
append(iterable<string|int, mixed> $items) : self
Parameters
- $items : iterable<string|int, mixed>
-
Items list.
Return values
selfappendItem()
Append a single item creating a new collection.
public
appendItem(mixed $item[, mixed $key = null ]) : self
Parameters
- $item : mixed
-
The item to append.
- $key : mixed = null
-
The key to append the item with. If null a key will be generated.
Return values
selfavg()
Returns the average of all the values extracted with $path or of this collection.
public
avg([callable|string|null $path = null ]) : float|int|null
Example:
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
The average of an empty set or 0 rows is null
. Collections with null
values are not considered empty.
Parameters
- $path : callable|string|null = null
-
The property name to compute the average or a function If no value is passed, an identity function will be used. that will return the value of the property to compute the average.
Return values
float|int|nullbuffered()
Returns a new collection where the operations performed by this collection.
public
buffered() : self
No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
Return values
selfcartesianProduct()
Create a new collection that is the cartesian product of the current collection
public
cartesianProduct([callable|null $operation = null ][, callable|null $filter = null ]) : self
In order to create a cartesian product a collection must contain a single dimension of data.
Example
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
Parameters
- $operation : callable|null = null
-
A callable that allows you to customize the product result.
- $filter : callable|null = null
-
A filtering callback that must return true for a result to be part of the final results.
Return values
selfchunk()
Breaks the collection into smaller arrays of the given size.
public
chunk(int $chunkSize) : self
Example:
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
Parameters
- $chunkSize : int
-
The maximum size for each chunk
Return values
selfchunkWithKeys()
Breaks the collection into smaller arrays of the given size.
public
chunkWithKeys(int $chunkSize[, bool $keepKeys = true ]) : self
Example:
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
Parameters
- $chunkSize : int
-
The maximum size for each chunk
- $keepKeys : bool = true
-
If the keys of the array should be kept
Return values
selfcombine()
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
public
combine(callable|string $keyPath, callable|string $valuePath[, callable|string|null $groupPath = null ]) : self
Examples:
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar'],
];
Parameters
- $keyPath : callable|string
-
the column name path to use for indexing or a function returning the indexing key out of the provided element
- $valuePath : callable|string
-
the column name path to use as the array value or a function returning the value out of the provided element
- $groupPath : callable|string|null = null
-
the column name path to use as the parent grouping key or a function returning the key out of the provided element
Return values
selfcompile()
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result.
public
compile([bool $keepKeys = true ]) : self
This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
Example:
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
In the above example, had the collection not been compiled before, the
iterations for map
, sortBy
and extract
would've been executed twice:
once for getting $isJohnHere
and once for $allButJohn
You can think of this method as a way to create save points for complex calculations in a collection.
Parameters
- $keepKeys : bool = true
-
Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
Return values
selfcontains()
Returns true if $value is present in this collection. Comparisons are made both by value and type.
public
contains(mixed $value) : bool
Parameters
- $value : mixed
-
The value to check for
Return values
bool —true if $value is present in this collection
count()
Returns the amount of elements in the collection.
public
count() : int
WARNINGS:
Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement)
or a unbuffered database cursor will not accept any other function calls after calling
count()
on it.
Create a new collection with buffered()
method to overcome this problem.
Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration
(the count of unique keys), you can call countKeys()
Return values
intcountBy()
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
public
countBy(callable|string $path) : self
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
Parameters
- $path : callable|string
-
The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
Return values
selfcountKeys()
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
public
countKeys() : int
This method comes with a number of caveats. Please refer to CollectionInterface::count()
for details.
Tags
Return values
inteach()
Applies a callback to the elements in this collection.
public
each(callable $callback) : $this
Example:
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
Parameters
- $callback : callable
-
Callback to run for each element in collection.
Return values
$thisevery()
Returns true if all values in this collection pass the truth test provided in the callback.
public
every(callable $callback) : bool
The callback is passed the value and key of the element being tested and should return true if the test passed.
Example:
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
Empty collections always return true.
Parameters
- $callback : callable
-
a callback function
Return values
bool —true if for all elements in this collection the provided callback returns true, false otherwise.
extract()
Returns a new collection containing the column or property value found in each of the elements.
public
extract(callable|string $path) : self
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
Example:
Extract the user name for all comments in the array:
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
It is also possible to extract a flattened collection out of nested properties
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
Parameters
- $path : callable|string
-
A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
Return values
selffilter()
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
public
filter([callable|null $callback = null ]) : self
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
Parameters
- $callback : callable|null = null
-
the method that will receive each of the elements and returns true whether they should be in the resulting collection. If left null, a callback that filters out falsey values will be used.
Return values
selffirst()
Returns the first result in this collection
public
first() : mixed
Return values
mixed —The first value in the collection will be returned.
firstMatch()
Returns the first result matching all the key-value pairs listed in conditions.
public
firstMatch(array<string|int, mixed> $conditions) : mixed
Parameters
- $conditions : array<string|int, mixed>
-
a key-value list of conditions where the key is a property path as accepted by
Collection::extract
, and the value the condition against with each element will be matched
Tags
groupBy()
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
public
groupBy(callable|string $path) : self
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
Parameters
- $path : callable|string
-
The column name to use for grouping or callback that returns the value. or a function returning the grouping key out of the provided element
Return values
selfindexBy()
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item.
public
indexBy(callable|string $path) : self
Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
Parameters
- $path : callable|string
-
The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
Return values
selfinsert()
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
public
insert(string $path, mixed $values) : self
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
Example:
Insert ages into a collection containing users:
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
Parameters
- $path : string
-
a dot separated string symbolizing the path to follow inside the hierarchy of each value so that the value can be inserted
- $values : mixed
-
The values to be inserted at the specified path, values are matched with the elements in this collection by its positional index.
Return values
selfisEmpty()
Returns whether there are elements in this collection
public
isEmpty() : bool
Example:
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
(new Collection([]))->isEmpty(); // true
Return values
booljsonSerialize()
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
public
jsonSerialize() : array<string|int, mixed>
Part of JsonSerializable interface.
Return values
array<string|int, mixed> —The data to convert to JSON
last()
Returns the last result in this collection
public
last() : mixed
Return values
mixed —The last value in the collection will be returned.
lazy()
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yielded one at a time.
public
lazy() : self
A lazy collection can only be iterated once. A second attempt results in an error.
Return values
selflistNested()
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
public
listNested([string|int $order = 'desc' ][, callable|string $nestingKey = 'children' ]) : self
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
- desc: RecursiveIteratorIterator::SELF_FIRST
- asc: RecursiveIteratorIterator::CHILD_FIRST
- leaves: RecursiveIteratorIterator::LEAVES_ONLY
Example:
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
Parameters
- $order : string|int = 'desc'
-
The order in which to return the elements
- $nestingKey : callable|string = 'children'
-
The key name under which children are nested or a callable function that will return the children list
Return values
selfmap()
Returns another collection after modifying each of the values in this one using the provided callable.
public
map(callable $callback) : self
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Getting a collection of booleans where true indicates if a person is female:
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
Parameters
- $callback : callable
-
the method that will receive each of the elements and returns the new value for the key that is being iterated
Return values
selfmatch()
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
public
match(array<string|int, mixed> $conditions) : self
Example:
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']],
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]]
]
Parameters
- $conditions : array<string|int, mixed>
-
a key-value list of conditions where the key is a property path as accepted by
Collection::extract
, and the value the condition against with each element will be matched
Return values
selfmax()
Returns the top element in this collection after being sorted by a property.
public
max(callable|string $path[, int $sort = SORT_NUMERIC ]) : mixed
Check the sortBy method for information on the callback and $sort parameters
Examples:
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
Parameters
- $path : callable|string
-
The column name to use for sorting or callback that returns the value.
- $sort : int = SORT_NUMERIC
-
The sort type, one of SORT_STRING, SORT_NUMERIC or SORT_NATURAL
Tags
Return values
mixed —The value of the top element in the collection
median()
Returns the median of all the values extracted with $path or of this collection.
public
median([callable|string|null $path = null ]) : float|int|null
Example:
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
The median of an empty set or 0 rows is null
. Collections with null
values are not considered empty.
Parameters
- $path : callable|string|null = null
-
The property name to compute the median or a function If no value is passed, an identity function will be used. that will return the value of the property to compute the median.
Return values
float|int|nullmin()
Returns the bottom element in this collection after being sorted by a property.
public
min(callable|string $path[, int $sort = SORT_NUMERIC ]) : mixed
Check the sortBy method for information on the callback and $sort parameters
Examples:
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
Parameters
- $path : callable|string
-
The column name to use for sorting or callback that returns the value.
- $sort : int = SORT_NUMERIC
-
The sort type, one of SORT_STRING, SORT_NUMERIC or SORT_NATURAL
Tags
Return values
mixed —The value of the bottom element in the collection
nest()
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
public
nest(callable|string $idPath, callable|string $parentPath[, string $nestingKey = 'children' ]) : self
Parameters
- $idPath : callable|string
-
the column name path to use for determining whether an element is a parent of another
- $parentPath : callable|string
-
the column name path to use for determining whether an element is a child of another
- $nestingKey : string = 'children'
-
The key name under which children are nested
Return values
selfprepend()
Prepend a set of items to a collection creating a new collection
public
prepend(mixed $items) : self
Parameters
- $items : mixed
-
The items to prepend.
Return values
selfprependItem()
Prepend a single item creating a new collection.
public
prependItem(mixed $item[, mixed $key = null ]) : self
Parameters
- $item : mixed
-
The item to prepend.
- $key : mixed = null
-
The key to prepend the item with. If null a key will be generated.
Return values
selfreduce()
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function.
public
reduce(callable $callback[, mixed $initial = null ]) : mixed
If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
Parameters
- $callback : callable
-
The callback function to be called
- $initial : mixed = null
-
The state of reduction
reject()
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
public
reject(callable $callback) : self
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
Parameters
- $callback : callable
-
the method that will receive each of the elements and returns true whether they should be out of the resulting collection.
Return values
selfsample()
Returns a new collection with maximum $length random elements from this collection
public
sample([int $length = 10 ]) : self
Parameters
- $length : int = 10
-
the maximum number of elements to randomly take from this collection
Return values
selfshuffle()
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
public
shuffle() : self
Return values
selfskip()
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
public
skip(int $length) : self
Parameters
- $length : int
-
The number of elements to skip.
Return values
selfsome()
Returns true if any of the values in this collection pass the truth test provided in the callback.
public
some(callable $callback) : bool
The callback is passed the value and key of the element being tested and should return true if the test passed.
Example:
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
Parameters
- $callback : callable
-
a callback function
Return values
bool —true if the provided callback returns true for any element in this collection, false otherwise
sortBy()
Returns a sorted iterator out of the elements in this collection, ranked based on the results of applying a callback function to each value.
public
sortBy(callable|string $path[, int $order = SORT_DESC ][, int $sort = SORT_NUMERIC ]) : self
The parameter $path can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
Example:
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
Parameters
- $path : callable|string
-
The column name to use for sorting or callback that returns the value.
- $order : int = SORT_DESC
-
The sort order, either SORT_DESC or SORT_ASC
- $sort : int = SORT_NUMERIC
-
The sort type, one of SORT_STRING, SORT_NUMERIC or SORT_NATURAL
Return values
selfstopWhen()
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
public
stopWhen(callable|array<string|int, mixed> $condition) : self
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
Get elements until the first unapproved message is found:
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
Parameters
- $condition : callable|array<string|int, mixed>
-
the method that will receive each of the elements and returns true when the iteration should be stopped. If an array, it will be interpreted as a key-value list of conditions where the key is a property path as accepted by
Collection::extract
, and the value the condition against with each element will be matched.
Return values
selfsumOf()
Returns the total sum of all the values extracted with $matcher or of this collection.
public
sumOf([callable|string|null $path = null ]) : float|int
Example:
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]],
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
Parameters
- $path : callable|string|null = null
-
The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
Return values
float|inttake()
Returns a new collection with maximum $length elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
public
take([int $length = 1 ][, int $offset = 0 ]) : self
Parameters
- $length : int = 1
-
the maximum number of elements to take from this collection
- $offset : int = 0
-
A positional offset from where to take the elements
Return values
selftakeLast()
Returns the last N elements of a collection
public
takeLast(int $length) : self
Example:
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
Parameters
- $length : int
-
The number of elements at the end of the collection
Return values
selfthrough()
Passes this collection through a callable as its first argument.
public
through(callable $callback) : self
This is useful for decorating the full collection with another object.
Example:
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
Parameters
- $callback : callable
-
A callable function that will receive this collection as first argument.
Return values
selftoArray()
Returns an array representation of the results
public
toArray([bool $keepKeys = true ]) : array<string|int, mixed>
Parameters
- $keepKeys : bool = true
-
Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
Return values
array<string|int, mixed>toList()
Returns an numerically-indexed array representation of the results.
public
toList() : array<string|int, mixed>
This is equivalent to calling toArray(false)
Return values
array<string|int, mixed>transpose()
Transpose rows and columns into columns and rows
public
transpose() : self
Example:
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
Return values
selfunfold()
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
public
unfold([callable|null $callback = null ]) : self
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
Example:
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
Using a transformer
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
Parameters
- $callback : callable|null = null
-
A callable function that will receive each of the items in the collection and should return an array or Traversable object
Return values
selfunwrap()
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
public
unwrap() : Traversable
Return values
Traversablezip()
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
public
zip(iterable<string|int, mixed> $items) : self
Example:
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
Parameters
- $items : iterable<string|int, mixed>
-
The collections to zip.
Return values
selfzipWith()
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
public
zipWith(iterable<string|int, mixed> $items, callable $callback) : self
The resulting element will be the return value of the $callable function.
Example:
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
Parameters
- $items : iterable<string|int, mixed>
-
The collections to zip.
- $callback : callable
-
The function to use for zipping the elements together.