Laravel Collection Public API: combine

November 30, 2016 —John Koster


The combine method is used to combine the keys of the collection the method was called on with the values of another collection or array (supplied as an argument for $values). This method is equivalent to using PHP's array_combine function. This method also returns a new Collection instance and does not modify the original collection instance.

The following example code shows a very simple example of the combine method being used to combine two simple collections:

3$firstCollection = collect(['green', 'red', 'yellow']);
4$secondCollection = collect(['avocado', 'apple', 'banana']);
6$combinedCollection = $firstCollection->combine($secondCollection);

After the code has executed, the $combinedCollection variable would have a value similar to the following:

1Collection {
2 #items: array:3 [
3 "green" => "avocado"
4 "red" => "apple"
5 "yellow" => "banana"
6 ]

It is important that both collections/arrays have the same length. If the collections do not have the same length, an ErrorException will be thrown stating that "Both parameters should have an equal number of elements".

You would get the same result if $secondCollection was just a regular PHP array:

3$firstCollection = collect(['green', 'red', 'yellow']);
4$simpleArray = ['avocado', 'apple', 'banana'];
6$combinedCollection = $firstCollection->combine($simpleArray);

Again, the value of $combinedCollection would be the same as before.

Some absolutely amazing

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.