Comparing two arrays and showing the difference according to each one
So I know there's an easy way to see the difference between two arrays using array_diff. Take a look at why I need something a bit more specific though:
Let's say we have these 2 arrays
$array1 $array2
1 1
2 开发者_如何学编程 -
- 3
4 4
- 5
6 -
The -
indicates it is missing from the opposing array.
If $array1
contains a missing element from $array2
, it must be dropped from $array1
.
If $array2
contains a missing element from $array1
, it must be added to $array1
.
If I simply perform array_diff($array1, $array2)
, it will only return me [2, 6]
. This isn't helpful in my scenario because I don't know which of the two arrays these items are missing from.
I did a bit of looking around and didn't seem to find out if there is a native php function that will distinguish the arrays the items are missing from.
What would be the best way to go about this? I was thinking of looping $array1
and checking it against $array2
and storing the results missing in a third array, and visa-versa for a fourth array.
Is that the best way? or is there an even easier, native function i can use?
$comparison1 = array_diff($array1, $array2);
$comparison2 = array_diff($array2, $array1);
精彩评论