kicaj
kicaj

Reputation: 2968

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?

Upvotes: -2

Views: 969

Answers (4)

mickmackusa
mickmackusa

Reputation: 47991

To achieve your desired result, you'll need to transfer the associative keys from the first array to the second array, then make a call of array_diff_assoc() so that comparisons are made "per element position". Demo

var_export(
    array_diff_assoc(
        $fields,
        array_combine(array_keys($fields), $answer)
    )
);

Output:

  '1x1' => 'k',
  '1x2' => 'B',
  '2x3' => 'Y',
  '3x1' => 'b',
)

array_diff() is unsuitable for this task because $answer[1] = 'b' and that removes $fields['3x1'] = 'b' from the result because keys are not considerd, only values are compared.

Upvotes: 0

Jean-Paul
Jean-Paul

Reputation: 378

The method isn't wrong, compare the 2 lists, they both contain b

Upvotes: 2

aslawin
aslawin

Reputation: 1981

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.

Upvotes: 2

Sifat Haque
Sifat Haque

Reputation: 6067

see you put 'b' into both the $answer and the $fields array .

so that's why it gives u such output .

Upvotes: 0

Related Questions