Laravel Collection Public API: merge

November 29, 2016 —John Koster

merge($items)

The merge methods merges the given $items with the items in the collection. The merge method will replace any item in the original collection's items if a string key with the same value exists in the supplied $items. If the $items keys are numeric, the new $items will be added to the end of the new collection's items. The merge method can accept either an array or a Collection instance. The merge method returns a new instance of Collection and does not modify the original collection instance.

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// Merge an array with the existing collection.
11$newCollection = $collection->merge(['fourth']);

After the above code has executed, the $newCollection variable will be an instance of Collection and contain a value similar to the following output:

1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=4)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'third' (length=5)
7 3 => string 'fourth' (length=6)

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.