Laravel 5 Collections: Executing a Function on Collection Elements and Values With mapSpread

April 22, 2018 —John Koster

The mapSpread method is used to execute a callback on a collection. If the collection contains nested collections, or Traversable objects, the mapSpread will supply the elements of the nested collections as the arguments to the callback function. This method is typically used in conjunction with the chunk method, but that is not a strict requirement.

The mapSpread method returns a new collection and does not modify the original collection.

#Signature

1public function mapSpread(
2 callable $callback
3);

#Example Use

The following example demonstrates the basic use of the mapSpread method. We will first create a series of numbers using PHP's range function; afterwards, we will split the collection into smaller pieces using the chunk method and then label each element with the mapSpread method:

1// Create a collection of numbers.
2$collection = collect(range(1,9));
3 
4// Split the collection into smaller pieces.
5$chunks = $collection->chunk(2);
6 
7$labeled = $chunks->mapSpread(function ($odd, $even) {
8 return "Odd: {$odd} Even: {$even}";
9});

After the above code has executed, the $labeled collection would contain the following values:

Index Value
0 Odd: 1 Even: 2
1 Odd: 3 Even: 4
2 Odd: 5 Even: 6
3 Odd: 7 Even: 8
4 Odd: 9 Even: 4

#Replicating the Behavior of the LINQ Zip Operator

We can use the mapSpread method to replicate the behavior of LINQ's Zip operator that was added in version 4 of the .NET Framework. LINQ's Zip operator enumerates two collections and allows a new collection to be created by executing a function against the items from the original collection, much like the mapSpread method.

The following example demonstrates how to replicate the behavior of LINQ's Zip operator by using the mapSpread method:

Replicating the Behavior of the LINQ Zip Operator:

1// Create a collection of numbers.
2$numbers = collect([
3 3, 5, 7
4]);
5 
6// Create a collection of words, represented the numbers.
7$words = collect([
8 'three', 'five', 'seven'
9]);
10 
11// Combine the collections.
12$results = $numbers->zip($words)
13 ->mapSpread(function ($a, $b) {
14 return $a.'='.$b;
15 });

After the above code has executed, the $results collection would contain the following values:

Results of Applying mapSpread to a Zipped Collection:

| Index | Value | | 0 | 3=three | | 1 | 5=five | | 2 | 7=seven |

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.