Hello dear Stack overflowers,
I'm trying to compare one collection with the name 'text1', with another collection 'text2'.
I would like to achieve that it puts all values, that 'text1' and 'text2' both have, into another collection.
I already tried using Diff and DiffKeys (see compare two collection arrays in laravel ).
But I was not fully able to understand how I could compare values of 2 collection against each other with these functions. It looked like to me that those 2 functions (Diff and DiffKeys) require an key, which I do not specifically use (yet) in extracting parts of my collections.
My 'text1' collection looks like this:
$text1 = collect('burger', 'cheese', 'bread', 'ham');
My 'text2' collection looks like this:
$text2 = collect('cheese', 'bread', 'tomato');
What I would like to extract from this, are all values that are in both 'text1' and 'text2'. So in this case, it should return:
'cheese', 'bread'
(since these values are both in 'text1' and 'text2')
Is there a simple way to achieve this?
Thank you very much for helping me out.
Regards
Dave
CodePudding user response:
You want the intersect
method available on Collections:
$intersect = $text1->intersect($text2);
$intersect->all(); // [1 => 'cheese', 2 => 'bread']
CodePudding user response:
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);