3

I have an 'dictionary' array such as this:

  $arr['a']=5;
  $arr['b']=9;
  $arr['as']=56;
  $arr['gbsdfg']=89;

And I need a method that, given a list of the array keys, I can retrieve the corresponding array values. In other words, I am looking for a built-in function for the following methods:

function GetArrayValues($arrDictionary, $arrKeys)
{
  $arrValues=array();
  foreach($arrKeys as $key=>$value)
  {
     $arrValues[]=$arrDictionary[$key]
  }
  return $arrValues;
}

I am so sick of writing this kind of tedious transformation that I have to find a built-in method to do this. Any ideas?

0

2 Answers 2

8

array_intersect_key

Sign up to request clarification or add additional context in comments.

Comments

0

If you have an array of keys as values you can use array_intersect_key combined with array_flip. For example:

$values = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$keys   = ['a', 'c'];

array_intersect_key($values, array_flip($keys));
// ['a' => 1, 'c' => 3]

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.