Reputation: 39
I'm trying to compare 2 collections, and put all values present in both into another collection.
So given these collections:
$text1 = collect('burger', 'cheese', 'bread', 'ham');
$text2 = collect('cheese', 'bread', 'tomato');
I would like to extract 'cheese' and 'bread'
Upvotes: 1
Views: 2108
Reputation: 12208
in this case you need intersect method:
The intersect method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection's keys:
$text1Collection = collect('burger', 'cheese', 'bread', 'ham');
$text2Collection = collect('cheese', 'bread', 'tomato');
$resultCollection =$text1Collection->intersect($text2Collection);
Upvotes: 2
Reputation: 10210
You want the intersect
method available on Collections:
$intersect = $text1->intersect($text2);
$intersect->all(); // [1 => 'cheese', 2 => 'bread']
Upvotes: 2