phparraysfilterassociative-arrayarray-difference

Even after sorting keys, array_diff() finds no differences between two associative arrays despite some elements having different values


I must be going crazy, I have a piece of code which iterates through a CSV file and goes through the records in our database. If the records in our csv file do no match the records in the database, then it will update the database accordingly.

To debug I printed the output of the two arrays. $dbEntry is the data already in the database. $entry is the data coming from the csv.

ksort($dbEntry);
ksort($entry);
var_dump($dbEntry);
echo "<br/>";
var_dump($entry);
echo "<br/>";
var_dump(array_diff($entry, $dbEntry));
echo "<br/>";
if ($overwrite == "on" && array_diff($entry,$dbEntry)) {
    //do sql update
{

The output is as follows:

array(11) { ["brand"]=> string(6) "xxx" ["id"]=> int(19220) ["lmf_comm"]=> int(0) ["lmf_pass"]=> int(0) ["period"]=> string(3) "Mar" ["pma"]=> string(6) "CEDUNA" ["sf_comm"]=> int(0) ["sf_pass"]=> int(34) ["tf_comm"]=> int(0) ["tf_pass"]=> int(0) ["year"]=> string(4) "2012" } 
array(11) { ["brand"]=> string(6) "xxx" ["id"]=> int(19220) ["lmf_comm"]=> string(1) "0" ["lmf_pass"]=> string(1) "0" ["period"]=> string(3) "Mar" ["pma"]=> string(6) "CEDUNA" ["sf_comm"]=> string(1) "0" ["sf_pass"]=> string(1) "0" ["tf_comm"]=> string(1) "0" ["tf_pass"]=> string(1) "0" ["year"]=> string(4) "2012" } 
array(0) { } 

Now i know they are different type casts but that shouldn't matter (it hasn't in the past). the index "sf_pass" is different - it is 34 in $dbEntry and 0 in $entry?

I don't understand why it is given me nothing on the array_diff and therefore not entering the if statement beneath where I have mysql update query.

EDIT:

And it really doesn't make sense because later in the CSV i get the following output from a different row. I don't understand why the following will give me the output i'm looking for, whilst another row with pretty much identical values and typecasts not give me the output i'm looking for

array(11) { ["brand"]=> string(4) "yyy" ["id"]=> int(12) ["lmf_comm"]=> int(0) ["lmf_pass"]=> int(8) ["period"]=> string(3) "Jan" ["pma"]=> string(8) "FIVEDOCK" ["sf_comm"]=> int(5) ["sf_pass"]=> int(4) ["tf_comm"]=> int(14) ["tf_pass"]=> int(28) ["year"]=> string(4) "2012" } 
array(11) { ["brand"]=> string(4) "yyy" ["id"]=> int(12) ["lmf_comm"]=> string(2) "32" ["lmf_pass"]=> string(1) "8" ["period"]=> string(3) "Jan" ["pma"]=> string(8) "FIVEDOCK" ["sf_comm"]=> string(1) "5" ["sf_pass"]=> string(1) "4" ["tf_comm"]=> string(2) "14" ["tf_pass"]=> string(2) "28" ["year"]=> string(4) "2012" } 
array(1) { ["lmf_comm"]=> string(2) "32" } 

Solution

  • By default, the array_diff function only checks for values. And it does not considered how many times the value is repeated.

    use array_diff_assoc. It compares the array key by key.