Jump to content

Using array_intersect with a master array and two sub arrays?


CarmenH

Recommended Posts

Hello,

 

I have three arrays of integers $arrayA, $arrayB, and $arrayC.  $ArrayA is a "master array" meaning the array I need to match the other two to.  $arrayB and $arrayC are generated by my functions in the application and meet specific criteria.  As such, arrays B and C will never have any intersecting values, but both should have matches in $arrayA, and I need to generate an array which contains only the values of arrayA which match either B or C.

 

  After finding some documentation here (http://www.metrocomp.mocsi.eu/w3/php/func_array_intersect.html)

 

I tried using array_intersect :

 

array_intersect ($arrayA, $arrayB, $arrayC)

 

However this does not work as described and returns no results as there are no values which are contained in all three arrays.

 

I wrote the below as a work around, and it works just fine but I would think there is a better way?

$temp1 = array_intersect($arrA, $arrB);
$temp2 = array_intersect($arrA, $arrC);
$temp3 = array_merge($temp1, $temp2);
$final_array = array_unique($temp3);

 

Thanks for looking!

Carmen

Link to comment
Share on other sites

That method is fine, but you could clean it up a bit without using all those temporary variables.

 

$arr = array_unique(
array_merge(
	array_intersect($arrA, $arrB),
	array_intersect($arrA, $arrC)
)
);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.