phparraysarray-intersectarray-flip

PHP array_intersect + array_flip with array that has values multiple times


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?


Solution

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

    array_unique(array_intersect_key($arr1, array_flip($arr2)))