Laravel 5 Collections: Creating Combination of Elements With crossJoin

April 22, 2018 —John Koster

The crossJoin method is used to join the items within the collection instance with the values of the input arrays, or collections, with all possible permutations expressed. The final output of the crossJoin method will be a Cartesian product, which can be useful for representing matrices, or to easily determine the cardinality of a combination of items.

#Signature

1public function crossJoin(
2 ...$lists
3);

#Example Use

For the following example, let's imagine we are building a system that will allow manufacturers to quickly determine the total number of products they will be manufacturing. The particular manufacturer we are working with is going to produce shirts with various colors, styles, and sizes.

The following table lists the various different properties of the clothing this manufacturer is looking to produce; each column represents a different unique property:

Color Style Size
Red polo XS
Blue V-neck S
Green M
L
XL
XXL

As you can see, within any one set of properties, there are not that many factors to take into consideration. However, things become much more complicated when we need to make decisions across all color, style, and size combinations.

We can use the crossJoin method to easily produce a list of all of the combinations like so:

1// Create our base collection.
2$colors = collect([
3 'Red', 'Blue', 'Green'
4]);
5 
6// Cross-join the other properties.
7$combinations = $colors->crossJoin(
8 ['polo', 'V-neck'], // Styles
9 ['XS', 'S', 'M', 'L', 'XL', 'XXL'] // Sizes
10);
11 
12// Determine the number of combinations.
13$numberOfCombinations = $combinations->count();

Once the above example has executed, the $numberOfCombinations variable would contain the value 36. This will let our platform inform the manufacturer that they need to accommodate thirty-six products in their production and distribution pipelines.

While this example was fairly trivial, the concepts explored can be applied to much more complicated and detailed problems.

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.