Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_diff() not returning differences found in the second array [duplicate]

I've read some tutorials on here but none of them return what I need. I have two arrays.

$arrayA = array(1960,1961,1963,1962,1954,1953,1957,1956,1955);
$arrayB = array(1949,1960,1961,1963,1962,1954,1953,1957,1956,1955);

However, when I run array_diff, it returns an empty array.

$diff = array_diff($arrayA, $arrayB);

But I'd like it to return 1949. What's the error in my code?

edit: since switching the variables won't work, i did var_dump for the 3 arrays (A, B, and diff) and here's the pastebin http://pastebin.com/tn1dvCs3

like image 622
user2036066 Avatar asked Oct 26 '25 01:10

user2036066


1 Answers

array_diff works by finding the elements in the first array that aren't in the second, per the documentation. Try inverting your call:

$diff = array_diff($arrayB, $arrayA);

To see this in action, lets look at a more manageable but equivalent example:

$arrayA = array(1960);
$arrayB = array(1949,1960);

$diff = array_diff($arrayB, $arrayA);
var_dump($diff);

This yields:

[mylogin@aserver ~]$ vim test.php
[mylogin@aserver ~]$ php test.php
array(1) {
  [0]=>
  int(1949)
}

Please note that this uses a minimal demonstrative example of the functionality you're attempting to get. By discarding unnecessary data in your actual implementation you can more quickly zero in on the problem you're having.

like image 65
Nathaniel Ford Avatar answered Oct 27 '25 16:10

Nathaniel Ford