tags:

views:

35

answers:

3

Hello !

It's late and I know it is a very simple question but right now I do not have an idea and deadline is near..

I've got two arrays:

$array1 = array(
  'a' => 'asdasd',
  'b' => 'gtrgrtg',
  'c' => 'fwefwefw',
  'd' => 'trhrtgr',
);
$array2 = array(
  'b', 'c'
);

What was the name of function to get a part of assoc array by keys from the second array ?

$result = array(
  'b' => 'gtrgrtg',
  'c' => 'fwefwefw',
);

Thanks !

+6  A: 

Try this:

array_intersect_key($array1, array_flip($array2)).
Bill Karwin
That was that ! Thanks. Shame to me. ;)
hsz
Wow! Somehow I've missed this function before today. Cool! http://php.net/array_intersect_key
artlung
A: 

I think there's no such function, so I will implement one:

function array_filter_keys($array, $keys) {
  $newarray = array();
  foreach ($keys as $key) {
    if (array_key_exists($key, $array)) $newarray[$key] = $array[$key];
  }
  return $newarray;
}
SHiNKiROU
A: 

I'm curious to see if there's a built in that does this. Here's how I would do it.

$result = array();
foreach ($array2 as $key) {
  if (array_key_exists($key, $array1) {
    $result[$key] = $array1[$key];
  }
}
artlung