Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_diff() handling duplicates in the second array, that exist in the first one

Tags:

arrays

php

This might be a really easy question but after trying to solve it for a couple of hours I think my brain is now searching in a very narrowed and specific angle for solutions. I might even be using the wrong functions!!

I have 2 arrays and I want ANY possible difference between the two arrays. This works fine for simple arrays such as:

Example:

$dummy1 = array("0" => "508", "1" => "548", "2" => "558", "3" => "538", "4" => "563", "5" => "543");
$dummy2 = array("0" => "518", "1" => "548", "2" => "558", "3" => "538", "4" => "563", "6" => "543");

on array_diff ($dummy2 , $dummy1 );

correctly outputs: Array ( [0] => 518 )

Problematic scenario: I have these 2 arrays, where the difference is that the second one has a duplicate value, i.e. has an extra value, which happens to be the same with one of the first array's values.

$array1 = array("0" => "508", "1" => "548", "2" => "558", "3" => "538", "4" => "563", "5" => "543");
$array2 = array("0" => "508", "1" => "508", "2" => "548", "3" => "558", "4" => "538", "5" => "563", "6" => "543");

echo count($array1).'<br>';
echo count($array2).'<br>'; //count is here for debugging purposes

Now on array_diff ($array2, $array1); //or a different diff_() function

I want to output: Array ( [0] => 508 ) // (that extra 508 value)

Basically, ANY possible difference between the two arrays.

What I tried:

  • reversing the arrays if the first check is empty
  • some weird/complicated mixtures with array_diff_assoc()
  • some other weird/complicated mixtures with array_intersect() and array_diff()

Thanks! I run out of ideas/experience.

like image 339
hahaha Avatar asked Nov 21 '25 22:11

hahaha


1 Answers

Just add the duplicate values to your output :

$array1 = array("0" => "508", "1" => "548", "2" => "558", "3" => "538", "4" => "563", "5" => "543");
$array2 = array("0" => "508", "1" => "508", "2" => "548", "3" => "558", "4" => "538", "5" => "563", "6" => "543");

var_dump(array_diff($array2, $array1) + array_diff_assoc($array2, array_unique($array2)));

Output:

array(1) { [1]=> string(3) "508" }  // Use array_values(OUTPUT) to reset keys if needed

You can also add array_diff_assoc($array1, array_unique($array1)) if needed, and if you want to deal with the case where there are differences AND duplicates, re-use array_unique on your output : var_dump(array_unique( ... ));

like image 170
Clément Malet Avatar answered Nov 23 '25 12:11

Clément Malet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!