phparraysfilteringassociative-arrayintersection

Filter an associative array to keep elements with keys found as values in another flat array


Given two arrays:

$foo = array('a', 'b', 'c');
$bar = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

Is there a built-in PHP function to produce the following result array?

$result = array('a' => 1, 'b' => 2, 'c' => 3);

I've been through the Array Functions list on php.net, but can't seem to find what I'm looking for. I know how to do it myself if need be, but I figured this might be a common-enough problem that there might be a built-in function that does it and didn't want to reinvent the wheel.


Solution

  • Another way using array_flip and array_intersect_keys:

    $foo = array('a', 'b', 'c'); 
    $bar = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    
    $common = array_intersect_key($bar, array_flip($foo));
    

    Output

    array(3) {
      ["a"]=>
      int(0)
      ["b"]=>
      int(1)
      ["c"]=>
      int(2)
    }