Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Somewhat simple PHP array intersection question

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?

like image 887
Lachlan McDonald Avatar asked Nov 16 '09 12:11

Lachlan McDonald


People also ask

How can I find the intersection of two arrays in PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How do I check if two arrays have the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

What is array intersect?

The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order. For example. Input: A[] = {1,4,3,2,5, 8,9} , B[] = {6,3,2,7,5} Output: {3,2,5}


3 Answers

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);
like image 67
Raz Avatar answered Sep 28 '22 07:09

Raz


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.

like image 30
Steve Claridge Avatar answered Sep 28 '22 08:09

Steve Claridge


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];
    }
}
like image 44
Gumbo Avatar answered Sep 28 '22 08:09

Gumbo