I have two arrays:
$arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,);
and
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
.
The following code does the job. I hope it is self-explanatory.
array_unique(array_intersect_key($arr1, array_flip($arr2)))