Thursday, April 21, 2011

Get from associative array only that elements which keys are specified

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 !

From stackoverflow
  • Try this:

    array_intersect_key($array1, array_flip($array2)).
    
    hsz : That was that ! Thanks. Shame to me. ;)
    artlung : Wow! Somehow I've missed this function before today. Cool! http://php.net/array_intersect_key
  • 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;
    }
    
  • 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];
      }
    }
    

0 comments:

Post a Comment