3

I have two arrays:

$arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,);

and

$arr2 = array(0 => 103, 1 => 104, 2 => 105) 

The result I want to get is

Array (103 => 250, 104 => 500)

I have tried working with

array_intersect(array_flip($arr1), $arr2);

but

array_flip($arr1)

gives something like

Array(103 => 250, 106 => 500)

thus, keys get lost and can not be intersected correctly. Is there a way to get the desired result?

Tris
  • 151
  • 1
  • 10
  • not unexpected that keys get lost - array_flip swaps keys and values, and since you have "duplicate" values, you will lose some keys. and you can use `array_intersect_keys()` instead, which uses keys instead of values for the intersection comparisons. – Marc B Jan 28 '16 at 15:05

2 Answers2

2

The following code does the job. I hope it is self-explanatory.

array_unique(array_intersect_key($arr1, array_flip($arr2)))
Ihor Burlachenko
  • 4,689
  • 1
  • 26
  • 25
  • 1
    perfect! I just needed to use the array_flip on the other array and then use array_intersect_key. Of cause! thanks :) – Tris Jan 28 '16 at 15:07
0

Using the standard php library functions for this might reduce the readability of the code. I would go with an explicit foreach loop that goes over $arr2.

$ans = array();

foreach($arr2 as $key) {
    if (isset($arr1[$key]) && !in_array($arr1[$key], $ans)) {
        $ans[$key] = $arr1[$key];
    }
}

This function should O(n*n) where n is the length of $arr2.

Scott
  • 12,077
  • 4
  • 27
  • 48