Reputation: 199
I have two arrays that I want to compare the items of
I have array A [hi,no,lo,yes,because] and array B [mick,tickle,fickle,pickle,ni,hi,no,lo,yes,because]
so I want to search every item in A and compare to every item in B and if there is a match return "there is a match"
Upvotes: 5
Views: 33527
Reputation: 3275
One-liner:
foreach ($elem in $A) { if ($B -contains $elem) { "there is a match" } }
But it may be more convenient to count matches:
$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
"{0} matches found" -f $c
Or if you want to check if arrays intersect at all:
foreach ($elem in $A) { if ($B -contains $elem) { "there is a match"; break } }
Or if you want to check if $A is a subset of $B:
$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
if ($c -eq $A.Count) { '$A is a subset of $B' }
Finally there's Compare-Object cmdlet which is actually better than all of the above. Example (outputs only elements that are present in both arrays):
Compare-Object -IncludeEqual -ExcludeDifferent $A $B
Upvotes: 11