FtDRbwLXw6
FtDRbwLXw6

Reputation: 28891

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.

Upvotes: 2

Views: 503

Answers (3)

Josh
Josh

Reputation: 8191

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)
}

Upvotes: 6

nikc.org
nikc.org

Reputation: 16952

It's a bit of a dirty hack, but it works:

function extractKeys($keys, $data) {
    extract($data);

    return call_user_func_array('compact', $keys);
}

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

var_dump(extractKeys($foo, $bar));

Output:

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

Upvotes: 1

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28891

After posting, I thought of one way of doing this:

array_intersect_key($bar, array_fill_keys($foo, NULL))

Though, this isn't really the concise, built-in function that I had hoped for, it's definitely better than constructing the resultant array manually.

Upvotes: 0

Related Questions