For optimisation purposes, I need to intersect two arrays and keep the least number of duplicate values from the two initial arrays in the resulting array.
The order of values in the resulting array is not important.
Another important constraint is time complexity as this will be executed in a big loop.
Why array_intersect doesn't work :
From Shawn Pyle in the PHP docs :
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.
Rules :
- Returns values of $arr1 that are in $arr2
- If $arr1 or $arr2 contain duplicate values, return the least number of values between the two
Examples :
intersect([1, 1, 2, 3, 4, 4, 5], [1, 3, 3, 5, 5])
returns[1, 3, 5]
intersect([1, 1, 2, 3, 4, 4, 5], [1, 1, 1, 3, 3, 5, 5])
returns[1, 1, 3, 5]
intersect([1, 1, 2, 3, 4, 4, 5, 5], [1, 3, 3, 5, 5])
returns[1, 3, 5, 5]
intersect([1, 1, 1], [1, 1, 1])
returns[1, 1, 1]
intersect([1, 2, 3], [1, 3, 2])
returns[1, 2, 3]