Collections

  • class Cake\Collection\Collection

The collection classes provide a set of tools to manipulate arrays orTraversable objects. If you have ever used underscore.js,you have an idea of what you can expect from the collection classes.

Collection instances are immutable; modifying a collection will instead generatea new collection. This makes working with collection objects more predictable asoperations are side-effect free.

Quick Example

Collections can be created using an array or Traversable object. You’ll alsointeract with collections every time you interact with the ORM in CakePHP.A simple use of a Collection would be:

  1. use Cake\Collection\Collection;
  2.  
  3. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  4. $collection = new Collection($items);
  5.  
  6. // Create a new collection containing elements
  7. // with a value greater than one.
  8. $overOne = $collection->filter(function ($value, $key, $iterator) {
  9. return $value > 1;
  10. });

You can also use the collection() helper function instead of newCollection():

  1. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2.  
  3. // These both make a Collection instance.
  4. $collectionA = new Collection($items);
  5. $collectionB = collection($items);

The benefit of the helper method is that it is easier to chain off of than(new Collection($items)).

The Collection\CollectionTrait allows you to integratecollection-like features into any Traversable object you have in yourapplication as well.

List of Methods

appendappendItemavg
bufferedchunkchunkWithKeys
combinecompilecontains
countByeachevery
extractfilterfirst
firstMatchgroupByindexBy
insertisEmptylast
listNestedmapmatch
maxmedianmin
nestprependprependItem
reducerejectsample
shuffleskipsome
sortBystopWhensumOf
takethroughtranspose
unfoldzip

Iterating

  • Cake\Collection\Collection::each(callable $c)

Collections can be iterated and/or transformed into new collections with theeach() and map() methods. The each() method will not create a newcollection, but will allow you to modify any objects within the collection:

  1. $collection = new Collection($items);
  2. $collection = $collection->each(function ($value, $key) {
  3. echo "Element $key: $value";
  4. });

The return of each() will be the collection object. Each will iterate thecollection immediately applying the callback to each value in the collection.

  • Cake\Collection\Collection::map(callable $c)

The map() method will create a new collection based on the output of thecallback being applied to each object in the original collection:

  1. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2. $collection = new Collection($items);
  3.  
  4. $new = $collection->map(function ($value, $key) {
  5. return $value * 2;
  6. });
  7.  
  8. // $result contains [2, 4, 6];
  9. $result = $new->toList();
  10.  
  11. // $result contains ['a' => 2, 'b' => 4, 'c' => 6];
  12. $result = $new->toArray();

The map() method will create a new iterator which lazily createsthe resulting items when iterated.

  • Cake\Collection\Collection::extract($matcher)

One of the most common uses for a map() function is to extract a singlecolumn from a collection. If you are looking to build a list of elementscontaining the values for a particular property, you can use the extract()method:

  1. $collection = new Collection($people);
  2. $names = $collection->extract('name');
  3.  
  4. // $result contains ['mark', 'jose', 'barbara'];
  5. $result = $names->toList();

As with many other functions in the collection class, you are allowed to specifya dot-separated path for extracting columns. This example will returna collection containing the author names from a list of articles:

  1. $collection = new Collection($articles);
  2. $names = $collection->extract('author.name');
  3.  
  4. // $result contains ['Maria', 'Stacy', 'Larry'];
  5. $result = $names->toList();

Finally, if the property you are looking after cannot be expressed as a path,you can use a callback function to return it:

  1. $collection = new Collection($articles);
  2. $names = $collection->extract(function ($article) {
  3. return $article->author->name . ', ' . $article->author->last_name;
  4. });

Often, the properties you need to extract a common key present in multiplearrays or objects that are deeply nested inside other structures. For thosecases you can use the {*} matcher in the path key. This matcher is oftenhelpful when matching HasMany and BelongsToMany association data:

  1. $data = [
  2. [
  3. 'name' => 'James',
  4. 'phone_numbers' => [
  5. ['number' => 'number-1'],
  6. ['number' => 'number-2'],
  7. ['number' => 'number-3'],
  8. ]
  9. ],
  10. [
  11. 'name' => 'James',
  12. 'phone_numbers' => [
  13. ['number' => 'number-4'],
  14. ['number' => 'number-5'],
  15. ]
  16. ]
  17. ];
  18.  
  19. $numbers = (new Collection($data))->extract('phone_numbers.{*}.number');
  20. $numbers->toList();
  21. // Returns ['number-1', 'number-2', 'number-3', 'number-4', 'number-5']

This last example uses toList() unlike other examples, which is importantwhen we’re getting results with possibly duplicate keys. By using toList()we’ll be guaranteed to get all values even if there are duplicate keys.

Unlike Cake\Utility\Hash::extract() this method only supports the{*} wildcard. All other wildcard and attributes matchers are not supported.

  • Cake\Collection\Collection::combine($keyPath, $valuePath, $groupPath = null)

Collections allow you to create a new collection made from keys and values inan existing collection. Both the key and value paths can be specified withdot notation paths:

  1. $items = [
  2. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  3. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  4. ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  5. ];
  6. $combined = (new Collection($items))->combine('id', 'name');
  7.  
  8. // Result will look like this when converted to array
  9. [
  10. 1 => 'foo',
  11. 2 => 'bar',
  12. 3 => 'baz',
  13. ];

You can also optionally use a groupPath to group results based on a path:

  1. $combined = (new Collection($items))->combine('id', 'name', 'parent');
  2.  
  3. // Result will look like this when converted to array
  4. [
  5. 'a' => [1 => 'foo', 3 => 'baz'],
  6. 'b' => [2 => 'bar']
  7. ];

Finally you can use closures to build keys/values/groups paths dynamically,for example when working with entities and dates (converted to Cake/Timeinstances by the ORM) you may want to group results by date:

  1. $combined = (new Collection($entities))->combine(
  2. 'id',
  3. function ($entity) { return $entity; },
  4. function ($entity) { return $entity->date->toDateString(); }
  5. );
  6.  
  7. // Result will look like this when converted to array
  8. [
  9. 'date string like 2015-05-01' => ['entity1->id' => entity1, 'entity2->id' => entity2, ..., 'entityN->id' => entityN]
  10. 'date string like 2015-06-01' => ['entity1->id' => entity1, 'entity2->id' => entity2, ..., 'entityN->id' => entityN]
  11. ]
  • Cake\Collection\Collection::stopWhen(callable $c)

You can stop the iteration at any point using the stopWhen() method. Callingit in a collection will create a new one that will stop yielding results if thepassed callable returns true for one of the elements:

  1. $items = [10, 20, 50, 1, 2];
  2. $collection = new Collection($items);
  3.  
  4. $new = $collection->stopWhen(function ($value, $key) {
  5. // Stop on the first value bigger than 30
  6. return $value > 30;
  7. });
  8.  
  9. // $result contains [10, 20];
  10. $result = $new->toList();
  • Cake\Collection\Collection::unfold(callable $c)

Sometimes the internal items of a collection will contain arrays or iteratorswith more items. If you wish to flatten the internal structure to iterate onceover all elements you can use the unfold() method. It will create a newcollection that will yield every single element nested in the collection:

  1. $items = [[1, 2, 3], [4, 5]];
  2. $collection = new Collection($items);
  3. $new = $collection->unfold();
  4.  
  5. // $result contains [1, 2, 3, 4, 5];
  6. $result = $new->toList();

When passing a callable to unfold() you can control what elements will beunfolded from each item in the original collection. This is useful for returningdata from paginated services:

  1. $pages = [1, 2, 3, 4];
  2. $collection = new Collection($pages);
  3. $items = $collection->unfold(function ($page, $key) {
  4. // An imaginary web service that returns a page of results
  5. return MyService::fetchPage($page)->toList();
  6. });
  7.  
  8. $allPagesItems = $items->toList();

If you are using PHP 5.5+, you can use the yield keyword inside unfold()to return as many elements for each item in the collection as you may need:

  1. $oddNumbers = [1, 3, 5, 7];
  2. $collection = new Collection($oddNumbers);
  3. $new = $collection->unfold(function ($oddNumber) {
  4. yield $oddNumber;
  5. yield $oddNumber + 1;
  6. });
  7.  
  8. // $result contains [1, 2, 3, 4, 5, 6, 7, 8];
  9. $result = $new->toList();
  • Cake\Collection\Collection::chunk($chunkSize)

When dealing with large amounts of items in a collection, it may make sense toprocess the elements in batches instead of one by one. For splittinga collection into multiple arrays of a certain size, you can use the chunk()function:

  1. $items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  2. $collection = new Collection($items);
  3. $chunked = $collection->chunk(2);
  4. $chunked->toList(); // [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

The chunk function is particularly useful when doing batch processing, forexample with a database result:

  1. $collection = new Collection($articles);
  2. $collection->map(function ($article) {
  3. // Change a property in the article
  4. $article->property = 'changed';
  5. })
  6. ->chunk(20)
  7. ->each(function ($batch) {
  8. myBulkSave($batch); // This function will be called for each batch
  9. });
  • Cake\Collection\Collection::chunkWithKeys($chunkSize)

Much like chunk(), chunkWithKeys() allows you to slice upa collection into smaller batches but with keys preserved. This is useful whenchunking associative arrays:

  1. $collection = new Collection([
  2. 'a' => 1,
  3. 'b' => 2,
  4. 'c' => 3,
  5. 'd' => [4, 5]
  6. ]);
  7. $chunked = $collection->chunkWithKeys(2)->toList();
  8. // Creates
  9. [
  10. ['a' => 1, 'b' => 2],
  11. ['c' => 3, 'd' => [4, 5]]
  12. ]

Filtering

  • Cake\Collection\Collection::filter(callable $c)

Collections make it easy to filter and create new collections based onthe result of callback functions. You can use filter() to create a newcollection of elements matching a criteria callback:

  1. $collection = new Collection($people);
  2. $ladies = $collection->filter(function ($person, $key) {
  3. return $person->gender === 'female';
  4. });
  5. $guys = $collection->filter(function ($person, $key) {
  6. return $person->gender === 'male';
  7. });
  • Cake\Collection\Collection::reject(callable $c)

The inverse of filter() is reject(). This method does a negative filter,removing elements that match the filter function:

  1. $collection = new Collection($people);
  2. $ladies = $collection->reject(function ($person, $key) {
  3. return $person->gender === 'male';
  4. });
  • Cake\Collection\Collection::every(callable $c)

You can do truth tests with filter functions. To see if every element ina collection matches a test you can use every():

  1. $collection = new Collection($people);
  2. $allYoungPeople = $collection->every(function ($person) {
  3. return $person->age < 21;
  4. });
  • Cake\Collection\Collection::some(callable $c)

You can see if the collection contains at least one element matching a filterfunction using the some() method:

  1. $collection = new Collection($people);
  2. $hasYoungPeople = $collection->some(function ($person) {
  3. return $person->age < 21;
  4. });
  • Cake\Collection\Collection::match(array $conditions)

If you need to extract a new collection containing only the elements thatcontain a given set of properties, you should use the match() method:

  1. $collection = new Collection($comments);
  2. $commentsFromMark = $collection->match(['user.name' => 'Mark']);
  • Cake\Collection\Collection::firstMatch(array $conditions)

The property name can be a dot-separated path. You can traverse into nestedentities and match the values they contain. When you only need the firstmatching element from a collection, you can use firstMatch():

  1. $collection = new Collection($comments);
  2. $comment = $collection->firstMatch([
  3. 'user.name' => 'Mark',
  4. 'active' => true
  5. ]);

As you can see from the above, both match() and firstMatch() allow youto provide multiple conditions to match on. In addition, the conditions can befor different paths, allowing you to express complex conditions to matchagainst.

Aggregation

  • Cake\Collection\Collection::reduce(callable $c)

The counterpart of a map() operation is usually a reduce. Thisfunction will help you build a single result out of all the elements in acollection:

  1. $totalPrice = $collection->reduce(function ($accumulated, $orderLine) {
  2. return $accumulated + $orderLine->price;
  3. }, 0);

In the above example, $totalPrice will be the sum of all single pricescontained in the collection. Note the second argument for the reduce()function takes the initial value for the reduce operation you areperforming:

  1. $allTags = $collection->reduce(function ($accumulated, $article) {
  2. return array_merge($accumulated, $article->tags);
  3. }, []);
  • Cake\Collection\Collection::min(string|callable $callback, $type = SORT_NUMERIC)

To extract the minimum value for a collection based on a property, just use themin() function. This will return the full element from the collection andnot just the smallest value found:

  1. $collection = new Collection($people);
  2. $youngest = $collection->min('age');
  3.  
  4. echo $youngest->name;

You are also able to express the property to compare by providing a path or acallback function:

  1. $collection = new Collection($people);
  2. $personYoungestChild = $collection->min(function ($person) {
  3. return $person->child->age;
  4. });
  5.  
  6. $personWithYoungestDad = $collection->min('dad.age');
  • Cake\Collection\Collection::max(string|callable $callback, $type = SORT_NUMERIC)

The same can be applied to the max() function, which will return a singleelement from the collection having the highest property value:

  1. $collection = new Collection($people);
  2. $oldest = $collection->max('age');
  3.  
  4. $personOldestChild = $collection->max(function ($person) {
  5. return $person->child->age;
  6. });
  7.  
  8. $personWithOldestDad = $collection->max('dad.age');
  • Cake\Collection\Collection::sumOf(string|callable $callback)

Finally, the sumOf() method will return the sum of a property of allelements:

  1. $collection = new Collection($people);
  2. $sumOfAges = $collection->sumOf('age');
  3.  
  4. $sumOfChildrenAges = $collection->sumOf(function ($person) {
  5. return $person->child->age;
  6. });
  7.  
  8. $sumOfDadAges = $collection->sumOf('dad.age');
  • Cake\Collection\Collection::avg($matcher = null)

Calculate the average value of the elements in the collection. Optionallyprovide a matcher path, or function to extract values to generate the averagefor:

  1. $items = [
  2. ['invoice' => ['total' => 100]],
  3. ['invoice' => ['total' => 200]],
  4. ];
  5.  
  6. // Average: 150
  7. $average = (new Collection($items))->avg('invoice.total');
  • Cake\Collection\Collection::median($matcher = null)

Calculate the median value of a set of elements. Optionally provide a matcherpath, or function to extract values to generate the median for:

  1. $items = [
  2. ['invoice' => ['total' => 400]],
  3. ['invoice' => ['total' => 500]],
  4. ['invoice' => ['total' => 100]],
  5. ['invoice' => ['total' => 333]],
  6. ['invoice' => ['total' => 200]],
  7. ];
  8.  
  9. // Median: 333
  10. $median = (new Collection($items))->median('invoice.total');

Grouping and Counting

  • Cake\Collection\Collection::groupBy($callback)

Collection values can be grouped by different keys in a new collection when theyshare the same value for a property:

  1. $students = [
  2. ['name' => 'Mark', 'grade' => 9],
  3. ['name' => 'Andrew', 'grade' => 10],
  4. ['name' => 'Stacy', 'grade' => 10],
  5. ['name' => 'Barbara', 'grade' => 9]
  6. ];
  7. $collection = new Collection($students);
  8. $studentsByGrade = $collection->groupBy('grade');
  9.  
  10. // Result will look like this when converted to array:
  11. [
  12. 10 => [
  13. ['name' => 'Andrew', 'grade' => 10],
  14. ['name' => 'Stacy', 'grade' => 10]
  15. ],
  16. 9 => [
  17. ['name' => 'Mark', 'grade' => 9],
  18. ['name' => 'Barbara', 'grade' => 9]
  19. ]
  20. ]

As usual, it is possible to provide either a dot-separated path for nestedproperties or your own callback function to generate the groups dynamically:

  1. $commentsByUserId = $comments->groupBy('user.id');
  2.  
  3. $classResults = $students->groupBy(function ($student) {
  4. return $student->grade > 6 ? 'approved' : 'denied';
  5. });
  • Cake\Collection\Collection::countBy($callback)

If you only wish to know the number of occurrences per group, you can do so byusing the countBy() method. It takes the same arguments as groupBy so itshould be already familiar to you:

  1. $classResults = $students->countBy(function ($student) {
  2. return $student->grade > 6 ? 'approved' : 'denied';
  3. });
  4.  
  5. // Result could look like this when converted to array:
  6. ['approved' => 70, 'denied' => 20]
  • Cake\Collection\Collection::indexBy($callback)

There will be certain cases where you know an element is unique for the propertyyou want to group by. If you wish a single result per group, you can use thefunction indexBy():

  1. $usersById = $users->indexBy('id');
  2.  
  3. // When converted to array result could look like
  4. [
  5. 1 => 'markstory',
  6. 3 => 'jose_zap',
  7. 4 => 'jrbasso'
  8. ]

As with the groupBy() function you can also use a property path ora callback:

  1. $articlesByAuthorId = $articles->indexBy('author.id');
  2.  
  3. $filesByHash = $files->indexBy(function ($file) {
  4. return md5($file);
  5. });
  • Cake\Collection\Collection::zip($elements)

The elements of different collections can be grouped together using thezip() method. It will return a new collection containing an array groupingthe elements from each collection that are placed at the same position:

  1. $odds = new Collection([1, 3, 5]);
  2. $pairs = new Collection([2, 4, 6]);
  3. $combined = $odds->zip($pairs)->toList(); // [[1, 2], [3, 4], [5, 6]]

You can also zip multiple collections at once:

  1. $years = new Collection([2013, 2014, 2015, 2016]);
  2. $salaries = [1000, 1500, 2000, 2300];
  3. $increments = [0, 500, 500, 300];
  4.  
  5. $rows = $years->zip($salaries, $increments)->toList();
  6. // Returns:
  7. [
  8. [2013, 1000, 0],
  9. [2014, 1500, 500],
  10. [2015, 2000, 500],
  11. [2016, 2300, 300]
  12. ]

As you can already see, the zip() method is very useful for transposingmultidimensional arrays:

  1. $data = [
  2. 2014 => ['jan' => 100, 'feb' => 200],
  3. 2015 => ['jan' => 300, 'feb' => 500],
  4. 2016 => ['jan' => 400, 'feb' => 600],
  5. ]
  6.  
  7. // Getting jan and feb data together
  8.  
  9. $firstYear = new Collection(array_shift($data));
  10. $firstYear->zip($data[0], $data[1])->toList();
  11.  
  12. // Or $firstYear->zip(...$data) in PHP >= 5.6
  13.  
  14. // Returns
  15. [
  16. [100, 300, 400],
  17. [200, 500, 600]
  18. ]

Sorting

  • Cake\Collection\Collection::sortBy($callback)

Collection values can be sorted in ascending or descending order based ona column or custom function. To create a new sorted collection out of the valuesof another one, you can use sortBy:

  1. $collection = new Collection($people);
  2. $sorted = $collection->sortBy('age');

As seen above, you can sort by passing the name of a column or property thatis present in the collection values. You are also able to specify a propertypath instead using the dot notation. The next example will sort articles bytheir author’s name:

  1. $collection = new Collection($articles);
  2. $sorted = $collection->sortBy('author.name');

The sortBy() method is flexible enough to let you specify an extractorfunction that will let you dynamically select the value to use for comparing twodifferent values in the collection:

  1. $collection = new Collection($articles);
  2. $sorted = $collection->sortBy(function ($article) {
  3. return $article->author->name . '-' . $article->title;
  4. });

In order to specify in which direction the collection should be sorted, you needto provide either SORT_ASC or SORT_DESC as the second parameter forsorting in ascending or descending direction respectively. By default,collections are sorted in descending direction:

  1. $collection = new Collection($people);
  2. $sorted = $collection->sortBy('age', SORT_ASC);

Sometimes you will need to specify which type of data you are trying to compareso that you get consistent results. For this purpose, you should supply a thirdargument in the sortBy() function with one of the following constants:

  • SORT_NUMERIC: For comparing numbers
  • SORT_STRING: For comparing string values
  • SORT_NATURAL: For sorting string containing numbers and you’d like thosenumbers to be order in a natural way. For example: showing “10” after “2”.
  • SORT_LOCALE_STRING: For comparing strings based on the current locale.

By default, SORT_NUMERIC is used:

  1. $collection = new Collection($articles);
  2. $sorted = $collection->sortBy('title', SORT_ASC, SORT_NATURAL);

Warning

It is often expensive to iterate sorted collections more than once. If youplan to do so, consider converting the collection to an array or simply usethe compile() method on it.

Working with Tree Data

  • Cake\Collection\Collection::nest($idPath, $parentPath)

Not all data is meant to be represented in a linear way. Collections make iteasier to construct and flatten hierarchical or nested structures. Creatinga nested structure where children are grouped by a parent identifier property iseasy with the nest() method.

Two parameters are required for this function. The first one is the propertyrepresenting the item identifier. The second parameter is the name of theproperty representing the identifier for the parent item:

  1. $collection = new Collection([
  2. ['id' => 1, 'parent_id' => null, 'name' => 'Birds'],
  3. ['id' => 2, 'parent_id' => 1, 'name' => 'Land Birds'],
  4. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle'],
  5. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull'],
  6. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish'],
  7. ['id' => 6, 'parent_id' => null, 'name' => 'Fish'],
  8. ]);
  9.  
  10. $collection->nest('id', 'parent_id')->toList();
  11. // Returns
  12. [
  13. [
  14. 'id' => 1,
  15. 'parent_id' => null,
  16. 'name' => 'Birds',
  17. 'children' => [
  18. ['id' => 2, 'parent_id' => 1, 'name' => 'Land Birds', 'children' => []],
  19. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle', 'children' => []],
  20. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull', 'children' => []],
  21. ]
  22. ],
  23. [
  24. 'id' => 6,
  25. 'parent_id' => null,
  26. 'name' => 'Fish',
  27. 'children' => [
  28. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish', 'children' => []],
  29. ]
  30. ]
  31. ];

Children elements are nested inside the children property inside each of theitems in the collection. This type of data representation is helpful forrendering menus or traversing elements up to certain level in the tree.

  • Cake\Collection\Collection::listNested($dir = 'desc', $nestingKey = 'children')

The inverse of nest() is listNested(). This method allows you to flattena tree structure back into a linear structure. It takes two parameters; thefirst one is the traversing mode (asc, desc or leaves), and the second one isthe name of the property containing the children for each element in thecollection.

Taking the input the nested collection built in the previous example, we canflatten it:

  1. $nested->listNested()->toList();
  2.  
  3. // Returns
  4. [
  5. ['id' => 1, 'parent_id' => null, 'name' => 'Birds', 'children' => [...]],
  6. ['id' => 2, 'parent_id' => 1, 'name' => 'Land Birds'],
  7. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle'],
  8. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull'],
  9. ['id' => 6, 'parent_id' => null, 'name' => 'Fish', 'children' => [...]],
  10. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish']
  11. ]

By default, the tree is traversed from the root to the leaves. You can alsoinstruct it to only return the leaf elements in the tree:

  1. $nested->listNested()->toList();
  2.  
  3. // Returns
  4. [
  5. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle'],
  6. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull'],
  7. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish']
  8. ]

Once you have converted a tree into a nested list, you can use the printer()method to configure how the list output should be formatted:

  1. $nested->listNested()->printer('name', 'id', '--')->toArray();
  2.  
  3. // Returns
  4. [
  5. 3 => 'Eagle',
  6. 4 => 'Seagull',
  7. 5 -> '--Clown Fish',
  8. ]

The printer() method also lets you use a callback to generate the keys andor values:

  1. $nested->listNested()->printer(
  2. function ($el) {
  3. return $el->name;
  4. },
  5. function ($el) {
  6. return $el->id;
  7. }
  8. );

Other Methods

  • Cake\Collection\Collection::isEmpty()

Allows you to see if a collection contains any elements:

  1. $collection = new Collection([]);
  2. // Returns true
  3. $collection->isEmpty();
  4.  
  5. $collection = new Collection([1]);
  6. // Returns false
  7. $collection->isEmpty();
  • Cake\Collection\Collection::contains($value)

Collections allow you to quickly check if they contain one particularvalue: by using the contains() method:

  1. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2. $collection = new Collection($items);
  3. $hasThree = $collection->contains(3);

Comparisons are performed using the === operator. If you wish to do loosercomparison types you can use the some() method.

  • Cake\Collection\Collection::shuffle()

Sometimes you may wish to show a collection of values in a random order. Inorder to create a new collection that will return each value in a randomizedposition, use the shuffle:

  1. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3]);
  2.  
  3. // This could return [2, 3, 1]
  4. $collection->shuffle()->toList();
  • Cake\Collection\Collection::transpose()

When you transpose a collection, you get a new collection containing a row madeof the each of the original columns:

  1. $items = [
  2. ['Products', '2012', '2013', '2014'],
  3. ['Product A', '200', '100', '50'],
  4. ['Product B', '300', '200', '100'],
  5. ['Product C', '400', '300', '200'],
  6. ]
  7. $transpose = (new Collection($items))->transpose()->toList();
  8.  
  9. // Returns
  10. [
  11. ['Products', 'Product A', 'Product B', 'Product C'],
  12. ['2012', '200', '300', '400'],
  13. ['2013', '100', '200', '300'],
  14. ['2014', '50', '100', '200'],
  15. ]

Withdrawing Elements

  • Cake\Collection\Collection::sample(int $size)

Shuffling a collection is often useful when doing quick statistical analysis.Another common operation when doing this sort of task is withdrawing a fewrandom values out of a collection so that more tests can be performed on those.For example, if you wanted to select 5 random users to which you’d like to applysome A/B tests to, you can use the sample() function:

  1. $collection = new Collection($people);
  2.  
  3. // Withdraw maximum 20 random users from this collection
  4. $testSubjects = $collection->sample(20);

sample() will take at most the number of values you specify in the firstargument. If there are not enough elements in the collection to satisfy thesample, the full collection in a random order is returned.

  • Cake\Collection\Collection::take(int $size, int $from)

Whenever you want to take a slice of a collection use the take() function,it will create a new collection with at most the number of values you specify inthe first argument, starting from the position passed in the second argument:

  1. $topFive = $collection->sortBy('age')->take(5);
  2.  
  3. // Take 5 people from the collection starting from position 4
  4. $nextTopFive = $collection->sortBy('age')->take(5, 4);

Positions are zero-based, therefore the first position number is 0.

  • Cake\Collection\Collection::skip(int $positions)

While the second argument of take() can help you skip some elements beforegetting them from the collection, you can also use skip() for the samepurpose as a way to take the rest of the elements after a certain position:

  1. $collection = new Collection([1, 2, 3, 4]);
  2. $allExceptFirstTwo = $collection->skip(2)->toList(); // [3, 4]
  • Cake\Collection\Collection::first()

One of the most common uses of take() is getting the first element in thecollection. A shortcut method for achieving the same goal is using thefirst() method:

  1. $collection = new Collection([5, 4, 3, 2]);
  2. $collection->first(); // Returns 5
  • Cake\Collection\Collection::last()

Similarly, you can get the last element of a collection using the last()method:

  1. $collection = new Collection([5, 4, 3, 2]);
  2. $collection->last(); // Returns 2

Expanding Collections

  • Cake\Collection\Collection::append(array|Traversable $items)

You can compose multiple collections into a single one. This enables you togather data from various sources, concatenate it, and apply other collectionfunctions to it very smoothly. The append() method will return a newcollection containing the values from both sources:

  1. $cakephpTweets = new Collection($tweets);
  2. $myTimeline = $cakephpTweets->append($phpTweets);
  3.  
  4. // Tweets containing cakefest from both sources
  5. $myTimeline->filter(function ($tweet) {
  6. return strpos($tweet, 'cakefest');
  7. });
  • Cake\Collection\Collection::appendItem($value, $key)

Allows you to append an item with an optional key to the collection. If youspecify a key that already exists in the collection, the value will not beoverwritten:

  1. $cakephpTweets = new Collection($tweets);
  2. $myTimeline = $cakephpTweets->appendItem($newTweet, 99);
  • Cake\Collection\Collection::prepend(array|Traversable $items)

The prepend() method will return a new collection containing the values fromboth sources:

  1. $cakephpTweets = new Collection($tweets);
  2. $myTimeline = $cakephpTweets->prepend($phpTweets);
  • Cake\Collection\Collection::prependItem($value, $key)

Allows you to prepend an item with an optional key to the collection. If youspecify a key that already exists in the collection, the value will not beoverwritten:

  1. $cakephpTweets = new Collection($tweets);
  2. $myTimeline = $cakephpTweets->prependItem($newTweet, 99);

Warning

When appending from different sources, you can expect some keys from bothcollections to be the same. For example, when appending two simple arrays.This can present a problem when converting a collection to an array usingtoArray(). If you do not want values from one collection to overrideothers in the previous one based on their key, make sure that you calltoList() in order to drop the keys and preserve all values.

Modifiying Elements

  • Cake\Collection\Collection::insert(string $path, array|Traversable $items)

At times, you may have two separate sets of data that you would like to insertthe elements of one set into each of the elements of the other set. This isa very common case when you fetch data from a data source that does not supportdata-merging or joins natively.

Collections offer an insert() method that will allow you to insert each ofthe elements in one collection into a property inside each of the elements ofanother collection:

  1. $users = [
  2. ['username' => 'mark'],
  3. ['username' => 'juan'],
  4. ['username' => 'jose']
  5. ];
  6.  
  7. $languages = [
  8. ['PHP', 'Python', 'Ruby'],
  9. ['Bash', 'PHP', 'Javascript'],
  10. ['Javascript', 'Prolog']
  11. ];
  12.  
  13. $merged = (new Collection($users))->insert('skills', $languages);

When converted to an array, the $merged collection will look like this:

  1. [
  2. ['username' => 'mark', 'skills' => ['PHP', 'Python', 'Ruby']],
  3. ['username' => 'juan', 'skills' => ['Bash', 'PHP', 'Javascript']],
  4. ['username' => 'jose', 'skills' => ['Javascript', 'Prolog']]
  5. ];

The first parameter for the insert() method is a dot-separated path ofproperties to follow so that the elements can be inserted at that position. Thesecond argument is anything that can be converted to a collection object.

Please observe that elements are inserted by the position they are found, thus,the first element of the second collection is merged into the firstelement of the first collection.

If there are not enough elements in the second collection to insert into thefirst one, then the target property will be filled with null values:

  1. $languages = [
  2. ['PHP', 'Python', 'Ruby'],
  3. ['Bash', 'PHP', 'Javascript']
  4. ];
  5.  
  6. $merged = (new Collection($users))->insert('skills', $languages);
  7.  
  8. // Will yield
  9. [
  10. ['username' => 'mark', 'skills' => ['PHP', 'Python', 'Ruby']],
  11. ['username' => 'juan', 'skills' => ['Bash', 'PHP', 'Javascript']],
  12. ['username' => 'jose', 'skills' => null]
  13. ];

The insert() method can operate array elements or objects implementing theArrayAccess interface.

Making Collection Methods Reusable

Using closures for collection methods is great when the work to be done is smalland focused, but it can get messy very quickly. This becomes more obvious whena lot of different methods need to be called or when the length of the closuremethods is more than just a few lines.

There are also cases when the logic used for the collection methods can bereused in multiple parts of your application. It is recommended that youconsider extracting complex collection logic to separate classes. For example,imagine a lengthy closure like this one:

  1. $collection
  2. ->map(function ($row, $key) {
  3. if (!empty($row['items'])) {
  4. $row['total'] = collection($row['items'])->sumOf('price');
  5. }
  6.  
  7. if (!empty($row['total'])) {
  8. $row['tax_amount'] = $row['total'] * 0.25;
  9. }
  10.  
  11. // More code here...
  12.  
  13. return $modifiedRow;
  14. });

This can be refactored by creating another class:

  1. class TotalOrderCalculator
  2. {
  3. public function __invoke($row, $key)
  4. {
  5. if (!empty($row['items'])) {
  6. $row['total'] = collection($row['items'])->sumOf('price');
  7. }
  8.  
  9. if (!empty($row['total'])) {
  10. $row['tax_amount'] = $row['total'] * 0.25;
  11. }
  12.  
  13. // More code here...
  14.  
  15. return $modifiedRow;
  16. }
  17. }
  18.  
  19. // Use the logic in your map() call
  20. $collection->map(new TotalOrderCalculator)
  • Cake\Collection\Collection::through(callable $c)

Sometimes a chain of collection method calls can become reusable in other partsof your application, but only if they are called in that specific order. Inthose cases you can use through() in combination with a class implementing__invoke to distribute your handy data processing calls:

  1. $collection
  2. ->map(new ShippingCostCalculator)
  3. ->map(new TotalOrderCalculator)
  4. ->map(new GiftCardPriceReducer)
  5. ->buffered()
  6. ...

The above method calls can be extracted into a new class so they don’t need tobe repeated every time:

  1. class FinalCheckOutRowProcessor
  2. {
  3. public function __invoke($collection)
  4. {
  5. return $collection
  6. ->map(new ShippingCostCalculator)
  7. ->map(new TotalOrderCalculator)
  8. ->map(new GiftCardPriceReducer)
  9. ->buffered()
  10. ...
  11. }
  12. }
  13.  
  14. // Now you can use the through() method to call all methods at once
  15. $collection->through(new FinalCheckOutRowProcessor);

Optimizing Collections

  • Cake\Collection\Collection::buffered()

Collections often perform most operations that you create using its functions ina lazy way. This means that even though you can call a function, it does notmean it is executed right away. This is true for a great deal of functions inthis class. Lazy evaluation allows you to save resources in situationswhere you don’t use all the values in a collection. You might not use all thevalues when iteration stops early, or when an exception/failure case is reachedearly.

Additionally, lazy evaluation helps speed up some operations. Consider thefollowing example:

  1. $collection = new Collection($oneMillionItems);
  2. $collection = $collection->map(function ($item) {
  3. return $item * 2;
  4. });
  5. $itemsToShow = $collection->take(30);

Had the collections not been lazy, we would have executed one million operations,even though we only wanted to show 30 elements out of it. Instead, our mapoperation was only applied to the 30 elements we used. We can alsoderive benefits from this lazy evaluation for smaller collections when wedo more than one operation on them. For example: calling map() twice andthen filter().

Lazy evaluation comes with its downside too. You could be doing the sameoperations more than once if you optimize a collection prematurely. Considerthis example:

  1. $ages = $collection->extract('age');
  2.  
  3. $youngerThan30 = $ages->filter(function ($item) {
  4. return $item < 30;
  5. });
  6.  
  7. $olderThan30 = $ages->filter(function ($item) {
  8. return $item > 30;
  9. });

If we iterate both youngerThan30 and olderThan30, the collection wouldunfortunately execute the extract() operation twice. This is becausecollections are immutable and the lazy-extracting operation would be done forboth filters.

Luckily we can overcome this issue with a single function. If you plan to reusethe values from certain operations more than once, you can compile the resultsinto another collection using the buffered() function:

  1. $ages = $collection->extract('age')->buffered();
  2. $youngerThan30 = ...
  3. $olderThan30 = ...

Now, when both collections are iterated, they will only call theextracting operation once.

Making Collections Rewindable

The buffered() method is also useful for converting non-rewindable iteratorsinto collections that can be iterated more than once:

  1. // In PHP 5.5+
  2. public function results()
  3. {
  4. ...
  5. foreach ($transientElements as $e) {
  6. yield $e;
  7. }
  8. }
  9. $rewindable = (new Collection(results()))->buffered();

Cloning Collections

  • Cake\Collection\Collection::compile(bool $preserveKeys = true)

Sometimes you need to get a clone of the elements from anothercollection. This is useful when you need to iterate the same set from differentplaces at the same time. In order to clone a collection out of another use thecompile() method:

  1. $ages = $collection->extract('age')->compile();
  2.  
  3. foreach ($ages as $age) {
  4. foreach ($collection as $element) {
  5. echo h($element->name) . ' - ' . $age;
  6. }
  7. }