I need to run a check as to whether an array coming from a form input is identical to an array pulled from a database. I haven't really used array_diff() much. Because I don't know exactly how the 2 arrays might differ, it seems that I must do the comparison twice, switching the parameters around, in order for the comparison to be complete:

if ((array_diff($first_array,$second_array)) || (array_diff($second_array,$first_array)))

I think the above will take into account all possibilities (or so my testing indicates), but I just want to make sure there isn't a better and cleaner way to do this.

    You only need to use array_diff() once since if it returns an empty array, the two arrays must not differ.

      no, array_diff returns values in the second array that are not in the first array. For example:

      $first_array = array(1,2,3);
      $second_array = array(1,2,3,4);

      If you do:
      $array_diff1 = array_diff($first_array, $second_array);

      The above returns an empty array

      However, if you do this:
      $array_diff2 = array_diff($second_array, $first_array);

      This returns an array: Array ( [3] => 4 )

        Oh yes, that is true, I did not consider the case where one array is a proper subset of the other. However, in that case a more efficient solution is to also check that the arrays are also of equal size.

        EDIT:
        Oh, that's wrong too, since disjoint sets would give a false positive.

        I think that the fastest way would just be to test if $first_array == $second_array after sorting the arrays. On the other hand, PHP may be able to optimise array_diff(), upon which your original idea would be more efficient.

        EDIT #2:
        Preliminary empirical testing shows that sorting the two arrays and then comparing with operator== is an order of magnitude faster than using array_diff() twice.

          Thanks! Your solution was the most obvious one, I just didn't realize you could compare arrays with ==. I just assumed it must be more complicated than that. 🙂

            Write a Reply...