21

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?

$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);

$C = array_intersect($A,$B);  //equals (1,2,3,4)
$A = array_diff($A,$B);       //equals (5,6,7,8)

Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.

kevtrout
  • 4,934
  • 6
  • 33
  • 33
  • It could be me, but I don't think the question is very clear. As I read it you are just interested in array_diff($A,$B) (which seems pretty simple). Or is the calculation of $C also essential? (If so, you can use array_diff($A,$C) instead of array_diff($A,$B).) – mweerden Oct 22 '08 at 13:16
  • No, I am declaring $C to be the intersection of $A and $B – kevtrout Oct 22 '08 at 17:58

5 Answers5

27

You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.

Edit: For example:

$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);

Source

Keyur
  • 1,113
  • 1
  • 23
  • 42
rg88
  • 20,742
  • 18
  • 76
  • 110
  • 2
    Also consider [array_diff_assoc](http://www.php.net/manual/en/function.array-diff-assoc.php) if the order of the values in the two arrays is important. – Duncanmoo Apr 23 '14 at 13:21
6

Dear easy and clean way

$clean1 = array_diff($array1, $array2); 
$clean2 = array_diff($array2, $array1); 
$final_output = array_merge($clean1, $clean2);
  • This answer is better, as it re-arrange the array elements on matching indexes. Unlike stuart's answer, which will remove elements from the matching indexes. So if there was a matching element at index 1, you try to access index 1 in result array, it will throw error. – Ajji Jan 23 '18 at 16:22
  • I don't know who stuart is, but asker's requirements do not mention any interest in respecting the indexes of the arrays. This answer is doing the same thing as rg88's answer and then calls `array_merge()` for some unknown reason. – mickmackusa Feb 22 '22 at 04:29
2

See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.

warren
  • 32,620
  • 21
  • 85
  • 124
0

Hey, even better solution: array _ uintersect. This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.

rg88
  • 20,742
  • 18
  • 76
  • 110
-1

Try to this

$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
$b = array(1=>'a',6=>'b',2=>'y',3=>'z');
$c = array_intersect($a, $b);

$result = array_diff($a, $c);
print_r($result);
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65