Laravel 5 Collections: Combining the Keys of a Collection With the Values of Another Collection With combine

April 22, 2018 —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 also returns a new Collection instance and does not modify the original collection instance.

The behavior of the combine method is similar to the behavior of PHP's array_combine function.

#Signature

1public function combine(
2 $values
3);

#Example Use

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

1$firstCollection = collect(['green', 'red', 'yellow']);
2$secondCollection = collect(['avocado', 'apple', 'banana']);
3 
4$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 "green" => "avocado"
4 "red" => "apple"
5 "yellow" => "banana"
6 ]
7}

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:

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

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

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.