5

I'm confusing array_diff behavior

why genre don't exist on diff array? Do you know how to resolve the matter?

-code

<?php
$array1 = array
(
    'value01' => '0',
    'value02' => 'v2',
    'genre' => '1',
    'type' => 'text',
    'contry' => 'us',
    'data' => '1',
);
$array2 = array
(
    'value01' => 'v1',
    'value02' => 'v2',
    'genre' => '0',
    'type' => 'text',
    'contry' => 'canada',
    'data' => '1',
);

print_r(array_diff($array1,$array2));

My result:

Array
(
    [contry] => us
)

But I expect:

Array
(
    [value01] => 0,
    [genre] => 1,
    [contry] => us,
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
freddiefujiwara
  • 57,041
  • 28
  • 76
  • 106

3 Answers3

18

I believe you want to use array_diff_assoc

http://www.php.net/manual/en/function.array-diff-assoc.php

scragz
  • 6,670
  • 2
  • 23
  • 23
5

array_diff operates on the values of the array, and ignores the keys.

Because the value of genre in your first array is 1, that means that if the value 1 occurs for any key in the second array, then the genre key will be removed from the first array.

Look at your arrays without the keys, and you'll see what I mean. You essentially have two lists of values, ['0','v2','1','text','us','1'] and ['v1','v2','0','text','canada','1']. The only value from the first list that doesn't appear in the second is 'us'.

I'm guessing you'll probably want to have a look at array_key_diff() or array_diff_assoc().

zombat
  • 92,731
  • 24
  • 156
  • 164
0

array_diff_assoc will cause Array to string conversion exception in case of multi depth associative arrays, for example arrays like these:

  "ip" => "127.0.0.1"
  "uri" => "follows/count"
  "body" => array:1 [
    "user_id" => 4473
  ]

For these types I have created a custom function which is generic, you can use that:

function mutidimensional_arrays_are_same(array $baseArray, array $compareArray)
{
    try {
        foreach ($baseArray as $key => $value) {
            if (is_array($value) && isset($compareArray[$key]) && is_array($compareArray[$key])) {
                return mutidimensional_arrays_are_same($value, $compareArray[$key]);
            } else {
                if ($value != $compareArray[$key]) {
                    return false;
                }
            }
        }
        return true;
    } catch (Exception $err) {
        return !str_starts_with($err->getMessage(), 'Undefined ');
    }
}

Unlike array_diff_assoc it returns boolean