Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array intersect on key in array?

Tags:

I have an array that has countries:

array(
'AF'=>'AFGHANISTAN',
'AL'=>'ALBANIA',
'DZ'=>'ALGERIA',
'AS'=>'AMERICAN SAMOA',
);

and I have another array that has some of the keys in it

array('AL', 'DZ');

I want to call a function that will take both arrays as parameters and return

array(
'AL'=>'ALBANIA',
'DZ'=>'ALGERIA',
);

I know php has built in functions to compare the keys, or the values, but it seems those functions all expect you to have two 1D arrays' or two 2D arrays.

I could loop over array_keys() for the first array and do a in_array() check on each key, but that seems really inefficent...

like image 267
Hailwood Avatar asked Jul 25 '12 07:07

Hailwood


People also ask

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.

What is Array_flip function in PHP?

The array_flip() function is used to exchange the keys with their associated values in an array. The function returns an array in flip order, i.e. keys from array become values and values from array become keys. Note: The values of the array need to be valid keys, i.e. they need to be either integer or string.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


2 Answers

$selection = array('AL', 'DZ');
$filtered = array_intersect_key($countries, array_flip($selection));
var_dump($filtered);
like image 136
deceze Avatar answered Sep 19 '22 08:09

deceze


Simply loop over the SECOND array, and fetch the values from the first. Vise versa seems unneeded inefficient indeed.

So:

$Arr1 = array(
'AF'=>'AFGHANISTAN',
'AL'=>'ALBANIA',
'DZ'=>'ALGERIA',
'AS'=>'AMERICAN SAMOA',
);

$Arr2 = array('AL', 'DZ');

$result = array();
foreach ($Arr2 as $cc){
  if (isset($Arr1[$cc])){
    $result[$cc] = $Arr1[$cc];
  }
}
print_r($result);

I don't think that is inefficient.

Edit addition: If you are 100% sure the $Arr2 contains only codes that can be found in $Arr1, you can of course skip the isset() test.

like image 26
Erwin Moller Avatar answered Sep 20 '22 08:09

Erwin Moller