1

The PHP function that I'm looking for is similar to array_intersect_key().

If I have an associative array called $populations[], and a numerical array called $countries[], which function will return a modified version of $populations[] with only keys present as values in $countries?

Here's a pair of arrays that I may want such a function for:

$populations = [
    'Sweden' => 6476727,
    'Denmark' => 3722898,
    'Finland' => 3417691,
    'Norway' => 3511912,
    'Iceland' => 247524
];

$countries = [
    'Sweden',
    'Denmark',
    'Norway'
];

Which function will take those two arrays as input, and output the following array?

['Sweden']=> 6476727
['Denmark']=> 3722898
['Norway']=> 3511912

3 Answers3

3

I don't think there's a single function that does it. But you can flip $countries into an associative array and then use array_intersect_key().

$result = array_intersect_key($populations, array_flip($countries));
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

With array_combine and array_map:

$result = array_combine(
  $countries,
  array_map(fn($country) => $populations[$country], $countries)
);

With array_reduce:

$result = array_reduce(
  $countries,
  function ($carry, $country) use ($populations) {
    $carry[$country] = $populations[$country];
    return $carry;
  },
  []
);

Or with array_reduce and an arrow function (the array_merge can become expensive if the resulting array becomes big):

$result = array_reduce(
  $countries,
  fn($carry, $country) => array_merge($carry, [ $country => $populations[$country] ]),
  []
);
lukas.j
  • 6,453
  • 2
  • 5
  • 24
0

Try out array_filter, you pass a simple custom callback closure that returns true if the item is to be included in the resulting array, in this case :in_array($key, $countries).

$populations = [
    'Sweden' => 6476727,
    'Denmark' => 3722898,
    'Finland' => 3417691,
    'Norway' => 3511912,
    'Iceland' => 247524
];

$countries = [
    'Sweden',
    'Denmark',
    'Norway'
];

$filtered = array_filter($populations, function($key) use ($countries) {
    return in_array($key, $countries);
}, ARRAY_FILTER_USE_KEY);

var_export($filtered);
/*
array (
  'Sweden' => 6476727,
  'Denmark' => 3722898,
  'Norway' => 3511912,
)
*/

Also, see PHP function use variable from outside

Note:

This will be less performant than Barmar's answer, but will be easier to understand when you revisit the code weeks, months, or years later.

Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31