hsz
hsz

Reputation: 152226

Get from associative array only that elements which keys are specified

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 !

Upvotes: 6

Views: 1489

Answers (3)

artlung
artlung

Reputation: 34013

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

Upvotes: 0

Ming-Tang
Ming-Tang

Reputation: 17651

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

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562378

Try this:

array_intersect_key($array1, array_flip($array2)).

Upvotes: 20

Related Questions