11

I'm trying to use array_diff like so. Here are my two array outputs:

List 1 Output

Array ([0] => 0022806 ) 

List 2 Output

Array ([0] => 0022806 [1] => 0023199 ) 

PHP

$diff = array_diff($list_1, $list_2);

print "DIFF: " . count($diff) ."<br>";
print_r($diff);

The Output is:

DIFF: 0
Array ( )

Any idea what I'm doing wrong? Why is 0023199 not returned?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user1216398
  • 1,890
  • 13
  • 32
  • 40
  • 2
    What if you invert the arguments? `Returns an array containing all the entries from array1 that are not present in any of the other arrays.` – Damien Pirsy Oct 16 '12 at 18:44

4 Answers4

22

The order of arguments in array_diff() is important

Returns an array containing all the entries from array1 that are not present in any of the other arrays

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    Is there a better way? I have no idea what the order may look like...I'm just interested in getting the delta between the two. – user1216398 Oct 16 '12 at 18:46
  • 1
    Do array_diff() both ways round, then array_merge() the results? That will give you teh entries that are in one array or the other, but not in both – Mark Baker Oct 16 '12 at 18:48
14

try;

$diff = array_merge(array_diff($list_1, $list_2), array_diff($list_2, $list_1));

print "DIFF: " . count($diff) ."<br>";
print_r($diff);
Mete Yarıcı
  • 151
  • 1
  • 4
2

From the docs:

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

If you only want to check whether they are the same, you can use $list1 == $list_2

JRL
  • 76,767
  • 18
  • 98
  • 146
1

Per the documentation, the values of the second array are subtracted from the first one. Or, to put it another way, you start with the first array, and then remove all the values that appear in the second array. That would correctly yield an empty array that you see above

You might want to play around with intersection, that might help you get what you want.

Landon
  • 4,088
  • 3
  • 28
  • 42