Get elements in an array based on keys stored in another

Viewed 56

I'm trying to use array_intersect to filter an existing array of countries down to just those whose country codes exist in another array.

$country_codes = array('UK','IRL');

$country_list = array(
      'ALB' => 'Albania',
      'AND' => 'Andorra',
      'ARM' => 'Armenia',
      'AUT' => 'Austria',
      'AZE' => 'Azerbaijan',
      'BLR' => 'Belarus',
      'BEL' => 'Belgium',
      'BIH' => 'Bosnia and Herzegovina',
      'BGR' => 'Bulgaria',
      'HRV' => 'Croatia',
      'CYP' => 'Cyprus',
      'CZE' => 'Czech Republic',
      'DNK' => 'Denmark',
      'EST' => 'Estonia',
      'FIN' => 'Finland',
      'FRA' => 'France',
      'GEO' => 'Georgia',
      'DEU' => 'Germany',
      'GRC' => 'Greece',
      'HUN' => 'Hungary',
      'ISL' => 'Iceland',
      'IRL' => 'Ireland',
      'ITA' => 'Italy',
      'KAZ' => 'Kazakhstan',
      'RKS' => 'Kosovo',
      'LVA' => 'Latvia',
      'LIE' => 'Liechtenstein',
      'LTU' => 'Lithuania',
      'LUX' => 'Luxembourg',
      'MLT' => 'Malta',
      'MDA' => 'Moldova',
      'MCO' => 'Monaco',
      'MNE' => 'Montenegro',
      'NLD' => 'Netherlands',
      'MKD' => 'North Macedonia',
      'NOR' => 'Norway',
      'POL' => 'Poland',
      'PRT' => 'Portugal',
      'ROU' => 'Romania',
      'RUS' => 'Russia',
      'SMR' => 'San Marino',
      'SRB' => 'Serbia',
      'SVK' => 'Slovakia',
      'SVN' => 'Slovenia',
      'ESP' => 'Spain',
      'SWE' => 'Sweden',
      'CHE' => 'Switzerland',
      'TUR' => 'Turkey',
      'UKR' => 'Ukraine',
      'UK' => 'UK',
    );

$filtered_countries = array_intersect($country_list, $country_codes);

My code seems to be half working...It is returning the 'UK' key but is ignoring the 'IRL' one.

When I print out the resulting array, I see this:

Array
(
    [UK] => UK
)

I'm expecting this:

Array
(
    [IRL] => Ireland
    [UK] => UK
)

Can anyone point me in the correct direction and explain why this is happening?

1 Answers

array_intersect() is based on values not keys. You can use array_intersect_key along with array_flip

$filtered_countries = array_intersect_key($country_list,  
                      array_flip($country_codes));
print_r($filtered_countries);

array_intersect_key — Computes the intersection of arrays using keys for comparison

array_flip — Exchanges all keys with their associated values in an array

Demo

Output:-

Array
(
    [IRL] => Ireland
    [UK] => UK
)
Related