Laravel 5

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


John Koster

Published on April 22, 2018

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.


1public function combine(
2 $values

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']);
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 ]

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'];
4$combinedCollection = $firstCollection->combine($simpleArray);

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

Explore The Blog