phplaraveldiffintersectionlaravel-collection

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?


Solution

  • 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,
         ],
       }