Somewhat simple PHP array crossing question

Maybe I'm going crazy, but I could swear there is a PHP core that took two arrays as arguments:

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

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

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

Is there such a function (which I skipped in the documentation), or is there a very optimized way to achieve the same?

+6
arrays php key intersection
source share
4 answers

try using array_flip {toggle keys with your own values} and then use array_intersect () in your example:

 $c = array_flip($b); // so you have your original b-array $intersect = array_intersect($a,c); 
+10
source share

I am not 100% understood what you want. Do you want to check values ​​from $ a against KEYS from $ b?

There are several crossing functions:

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

But maybe you need:

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

+2
source share

Make 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]; } } 
+1
source share

It’s just that Gumbo’s answer option should be more efficient, since 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]; } 
0
source share

All Articles