Michel Gisenaël
Michel Gisenaël

Reputation: 351

Laravel collection opposite of diff

I have 2 collections:

$collection = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);

with:

$collection->diff($collection2);

I get [2,3]

I want is to have the opposite values: [1,4]

Is there a way or method in collection to make this?

Upvotes: 0

Views: 1400

Answers (2)

ManojKiran
ManojKiran

Reputation: 6341

You can use duplicates method after mergging into single collection

$collection1 = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);

$duplicates = $collection1
  ->merge($collection2)
  ->duplicates()
  ->unique() // use this if you need the duplicates as unique
  ->values();

Will give you

Illuminate\Support\Collection {#1151
     all: [
       1,
       4,
     ],
   }

Upvotes: 1

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

laravel collection intersect

intersect method removes any values from the original collection that are not present in the given array or collection.

$collection = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);

$intersect = $collection->intersect($collection2);

$intersect->all();

Upvotes: 2

Related Questions