phparraysfilterassociative-arrayarray-difference

Find differences between two flat arrays of equal size by respective element position


I need to determine the elements in my $fields array which do not have the same value in the same-positioned element of my $answer array.

$fields = array(
    '1x1' => 'k',  // first element
    '1x2' => 'B',  // second element
    '1x3' => 'c',  // third element
    '2x1' => 'd',  // fourth element
    '2x2' => 'x',  // fifth element
    '2x3' => 'Y',  // sixth element
    '3x1' => 'b',  // seventh element
    '3x2' => 'e',  // eighth element
    '3x3' => 'f'   // ninth element
);

$answer = array(
    'a',  // first element
    'b',  // second element
    'c',  // third element
    'd',  // fourth element
    'x',  // fifth element
    'y',  // sixth element
    'z',  // seventh element
    'e',  // eighth element
    'f'   // ninth element
);

print_r(array_diff($fields, $answer));

Current result:

(
    [1x1] => k
    [1x2] => B
    [2x3] => Y
)

Desired result:

(
    [1x1] => k    // first elements value differs
    [1x2] => B    // second element value differs
    [2x3] => Y    // sixth element value differs
    [3x1] => b    // seventh element value differs
)

In the seventh element, $answer has z, but $fields has b. How do I get '3x1' => 'b' included in the result?


Solution

  • This is working correct. According to array_diff() documentation:

    array array_diff ( array $array1 , array $array2 [, array $... ] )

    Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

    Another important info from documentation:

    Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

    So in $answers array there are no k, B, Y elements of $fields array.