6

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 !

3 Answers 3

20

Try this:

array_intersect_key($array1, array_flip($array2)).
Sign up to request clarification or add additional context in comments.

2 Comments

That was that ! Thanks. Shame to me. ;)
Wow! Somehow I've missed this function before today. Cool! php.net/array_intersect_key
0

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

Comments

0

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];
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.