I hope this question has a really quick, simple answer. I have two arrays and I'd like to quickly compare them to see if they match and, if they don't match, what their differences are. Ideally the output would be a string like what you get from diff filea fileb.

I could certainly write a function to create two temporary files and call diff, but was wondering if there's some PHP function that will generate such a string for two arrays or strings. I have in the past always had to perform two array_diff calls:

$a = [1,2,3];
$b = [3,4,5];
echo "a not b\n";
print_r()array_diff($a, $b));
echo "b not a\n";
print_r()array_diff($b, $a));

which is quite clunky, IMHO. Also, the output shows one array's extras and then the other array's extras and doesn't give you a feel for the differences item-by-item as they occur.

    It's not a trivial question to say "what the differences are": look at a diff implementation to see the sort of thing that is involved.

    In your example, for example, the two arrays are different because "1" is replaced by "3", "2" is replaced by "4", and "3" is replaced by "5". No, wait, it's because "1" and "2" have been dropped from the beginning, and "4" and "5" have been added to the end; the "3" is just a "3".

    Then there's

    $a = [1, 2, 3];
    $b = [1, 3, 2];
    

    where "2" was removed from the middle of the array, and then "2" was added to the end of the array. Or maybe it was "3" inserted into the middle of the array and "3" removed from the end. Or maybe the "2" was just moved. Or the "3". Or maybe it doesn't matter and the arrays are to be considered "the same".

      Feels like one of those questions where maybe we need a better understanding of the actual functional requirement you're trying to solve (as opposed to "how do I solve it this way?"). E.g.: if those 2 sample arrays were files with one number per line, diff would say all 3 lines were different, which I don't think is the answer you're looking for???

        Write a Reply...