views:

410

answers:

4

Maybe I'm going insane, but I could have sworn that there was an PHP core function which took two arrays as arguments:

$a = array('1', '3');
$b = array('1'=>'apples', '2'=>'oranges', '3'=>'kiwis');

And performs an intersection where the values from array $a are checked for collisions with the keys in array $b. Returning something like

array('1'=>'apples', '3'=>'kiwis');

Does such a function exist (which I missed in the documentation), or is there a very optimized way to achieve the same thing?

+4  A: 

try using array_flip {switches keys with their values} and then use array_intersect() on your example :

$c = array_flip($b); // so you have your original b-array
$intersect = array_intersect($a,c);
Raz
This would work for the given example, but does not allow for duplicate values in $b. I'd do the variation of flipping $a (as it is supposed to hold keys anyway) and do `array_intersect_key($b, array_flip($a))`.
Henrik Opel
good point on the duplicates, didn't think of that one
Raz
`array_intersect_key($b, array_flip($a))` turns out to do the job. Cheers!
Lachlan McDonald
+2  A: 

I'm not 100% clear what you want. Do you want to check values from $a against KEYS from $b?

There's a few intersect functions:

http://php.net/manual/en/function.array-intersect.php http://www.php.net/manual/en/function.array-intersect-key.php

But possibly you need:

http://www.php.net/manual/en/function.array-intersect-ukey.php so that you can define your own function for matching keys and/or values.

Steve Claridge
+1  A: 

Do a simple foreach to iterate the first array and get the corresponding values from the second array:

$output = array();
foreach ($a as $key) {
    if (array_key_exists($key, $b)) {
        $output[$key] = $b[$key];
    }
}
Gumbo
A: 

Just a variation of the Gumbo answer, should be more efficient as the tests on the keys are performed just before entering the loop.

$intersection = array_intersect($a, array_keys($b));
$result=array();
foreach ($intersection as $key) {
    $result[$k]=$b[$k];
}
Eineki