Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Explain Collections Methods Part-I

  1. all
  2. average
  3. avg
  4. chunk
  5. chunkWhile
  6. collapse
  7. collect
  8. combine
  9. concat
  10. contains
  11. containsOneItem
  12. containsStrict
  13. count
  14. countBy
  15. crossJoin
  16. dd
  17. diff
  18. diffAssoc
  19. diffKeys
  20. doesntContain
  21. dump
  22. duplicates
  23. duplicatesStrict

Important used Collections Methods
all()
avg()
chunk()
collapse()
collect()
combine()
contains()

// [0, 0, 'A', 'B', 'C']

all()
The all method returns the underlying array represented by the collection:

collect([1, 2, 3])->all();

// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

average()
Alias for the avg method.

avg()
The avg method returns the average value of a given key:

$average = collect([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
])->avg('foo');

// 20
Enter fullscreen mode Exit fullscreen mode
$average = collect([1, 1, 2, 4])->avg();
Enter fullscreen mode Exit fullscreen mode
// 2
Enter fullscreen mode Exit fullscreen mode

chunk()
The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->all();

// [[1, 2, 3, 4], [5, 6, 7]]
Enter fullscreen mode Exit fullscreen mode

This method is especially useful in views when working with a grid system such as Bootstrap. For example, imagine you have a collection of Eloquent models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach
Enter fullscreen mode Exit fullscreen mode

chunkWhile()
The chunkWhile method breaks the collection into multiple, smaller collections based on the evaluation of the given callback. The $chunk variable passed to the closure may be used to inspect the previous element:

$collection = collect(str_split('AABBCCCD'));

$chunks = $collection->chunkWhile(function ($value, $key, $chunk) {
    return $value === $chunk->last();
});

$chunks->all();

// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]
Enter fullscreen mode Exit fullscreen mode

collapse()
The collapse method collapses a collection of arrays into a single, flat collection:

$collection = collect([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);

$collapsed = $collection->collapse();

$collapsed->all();

// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

collect()
The collect method returns a new Collection instance with the items currently in the collection:

$collectionA = collect([1, 2, 3]);

$collectionB = $collectionA->collect();

$collectionB->all();

// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

The collect method is primarily useful for converting lazy collections into standard Collection instances:

$lazyCollection = LazyCollection::make(function () {
    yield 1;
    yield 2;
    yield 3;
});

$collection = $lazyCollection->collect();

get_class($collection);
Enter fullscreen mode Exit fullscreen mode
// 'Illuminate\Support\Collection'

$collection->all();

// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

The collect method is especially useful when you have an instance of Enumerable and need a non-lazy collection instance. Since collect() is part of the Enumerable contract, you can safely use it to get a Collection instance.

combine()
The combine method combines the values of the collection, as keys, with the values of another array or collection:

$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]
Enter fullscreen mode Exit fullscreen mode

**concat()
**The concat method appends the given array or collection's values onto the end of another collection:

$collection = collect(['John Doe']);

$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']
Enter fullscreen mode Exit fullscreen mode

The concat method numerically reindexes keys for items concatenated onto the original collection. To maintain keys in associative collections, see the merge method.

contains()
The contains method determines whether the collection contains a given item. You may pass a closure to the contains method to determine if an element exists in the collection matching a given truth test:

$collection = collect([1, 2, 3, 4, 5]);

$collection->contains(function ($value, $key) {
    return $value > 5;
});

// false
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may pass a string to the contains method to determine whether the collection contains a given item value:

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false
Enter fullscreen mode Exit fullscreen mode

You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false
Enter fullscreen mode Exit fullscreen mode

The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict method to filter using "strict" comparisons.

For the inverse of contains, see the doesntContain method.

containsOneItem()
The containsOneItem method determines whether the collection contains a single item:

collect([])->containsOneItem();

// false

collect(['1'])->containsOneItem();

// true

collect(['1', '2'])->containsOneItem();

// false
Enter fullscreen mode Exit fullscreen mode

containsStrict()
This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.

count()
The count method returns the total number of items in the collection:

$collection = collect([1, 2, 3, 4]);

$collection->count();

// 4
Enter fullscreen mode Exit fullscreen mode

countBy()
The countBy method counts the occurrences of values in the collection. By default, the method counts the occurrences of every element, allowing you to count certain "types" of elements in the collection:

$collection = collect([1, 2, 2, 2, 3]);

$counted = $collection->countBy();

$counted->all();

// [1 => 1, 2 => 3, 3 => 1]
Enter fullscreen mode Exit fullscreen mode

You pass a closure to the countBy method to count all items by a custom value:

$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);

$counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
});

$counted->all();

// ['gmail.com' => 2, 'yahoo.com' => 1]
Enter fullscreen mode Exit fullscreen mode

crossJoin()
The crossJoin method cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations:

$collection = collect([1, 2]);

$matrix = $collection->crossJoin(['a', 'b']);

$matrix->all();

/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

$collection = collect([1, 2]);

$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);

$matrix->all();

/*
    [
        [1, 'a', 'I'],
        [1, 'a', 'II'],
        [1, 'b', 'I'],
        [1, 'b', 'II'],
        [2, 'a', 'I'],
        [2, 'a', 'II'],
        [2, 'b', 'I'],
        [2, 'b', 'II'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

dd()
The dd method dumps the collection's items and ends execution of the script:

$collection = collect(['John Doe', 'Jane Doe']);

$collection->dd();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/
Enter fullscreen mode Exit fullscreen mode

If you do not want to stop executing the script, use the dump method instead.

diff()
The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection:

$collection = collect([1, 2, 3, 4, 5]);

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

This method's behavior is modified when using Eloquent Collections.

diffAssoc()
The diffAssoc method compares the collection against another collection or a plain PHP array based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6,
]);

$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6,
]);

$diff->all();

// ['color' => 'orange', 'remain' => 6]
Enter fullscreen mode Exit fullscreen mode

diffKeys()
The diffKeys method compares the collection against another collection or a plain PHP array based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = collect([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);

$diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);

$diff->all();

// ['one' => 10, 'three' => 30, 'five' => 50]
Enter fullscreen mode Exit fullscreen mode

doesntContain()
The doesntContain method determines whether the collection does not contain a given item. You may pass a closure to the doesntContain method to determine if an element does not exist in the collection matching a given truth test:

$collection = collect([1, 2, 3, 4, 5]);

$collection->doesntContain(function ($value, $key) {
    return $value < 5;
});

// false
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may pass a string to the doesntContain method to determine whether the collection does not contain a given item value:

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->doesntContain('Table');

// true

$collection->doesntContain('Desk');

// false
Enter fullscreen mode Exit fullscreen mode

You may also pass a key / value pair to the doesntContain method, which will determine if the given pair does not exist in the collection:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->doesntContain('product', 'Bookcase');

// true
Enter fullscreen mode Exit fullscreen mode

The doesntContain method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value.

dump()
The dump method dumps the collection's items:

$collection = collect(['John Doe', 'Jane Doe']);

$collection->dump();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/
Enter fullscreen mode Exit fullscreen mode

duplicates()
The duplicates method retrieves and returns duplicate values from the collection:

$collection = collect(['a', 'b', 'a', 'c', 'b']);

$collection->duplicates();

// [2 => 'a', 4 => 'b']
Enter fullscreen mode Exit fullscreen mode

If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values:

$employees = collect([
    ['email' => 'abigail@example.com', 'position' => 'Developer'],
    ['email' => 'james@example.com', 'position' => 'Designer'],
    ['email' => 'victoria@example.com', 'position' => 'Developer'],
]);

$employees->duplicates('position');

// [2 => 'Developer']
Enter fullscreen mode Exit fullscreen mode

duplicatesStrict()
This method has the same signature as the duplicates method; however, all values are compared using "strict" comparisons.
If you want to stop executing the script after dumping the collection, use the dd method instead.

Top comments (0)