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
2
Answers
I don’t think there’s a single function that does it. But you can flip
$countries
into an associative array and then usearray_intersect_key()
.Try out
array_filter
, you pass a simple custom callback closure that returnstrue
if the item is to be included in the resulting array, in this case :in_array($key, $countries)
.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.