12

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?

1
  • 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. Commented Oct 16, 2012 at 18:44

4 Answers 4

23

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
16

try;

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

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

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.