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

Those two solutions are great !  I think I'll implement the second one.  Thank you!  :D

 

I just look back at my code.  Only use with arrays that are numerically indexed, not with associative arrays.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.