skip to Main Content

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


  1. 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));
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search