'array_diff to compare two associative arrays
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,
);
Solution 1:[1]
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().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zombat |
