PHP built-in method to get array values ​​given a list of keys

I have an array of dictionaries, for example:

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

And I need a method that, given the list of keys in the array, I can get 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'm so sick of writing such tedious conversions that I have to find a built-in method for this. Any ideas?

+3
source share
2 answers

If you have an array of keys as values, you can use array_intersect_keyin conjunction 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]
0
source

Source: https://habr.com/ru/post/1717793/


All Articles