PHP array function that returns a subset for given keys

user1517081 picture user1517081 · Sep 22, 2012 · Viewed 7.4k times · Source

I'm looking for an array function that does something like this:

$myArray = array(
  'apple'=>'red',
  'banana'=>'yellow',
  'lettuce'=>'green',
  'strawberry'=>'red',
  'tomato'=>'red'
);
$keys = array(
  'lettuce',
  'tomato'
);

$ret = sub_array($myArray, $keys);

where $ret is:

array(
  'lettuce'=>'green',
  'tomato'=>'red'
);

A have no problem in writing it down by myself, the thing is I would like to avoid foreach loop and adopt a built-in function or a combination of built-in functions. It seems to me like a general and common array operation - I'd be surprised if a loop is the only option.

Answer

Maciej Lew picture Maciej Lew · Jan 19, 2015

This works:

function sub_array(array $haystack, array $needle)
{
    return array_intersect_key($haystack, array_flip($needle));
}

$myArray = array(
    'apple'=>'red',
    'banana'=>'yellow',
    'lettuce'=>'green',
    'strawberry'=>'red',
    'tomato'=>'red'
);
$keys = array(
    'lettuce',
    'tomato'
);

$ret = sub_array($myArray, $keys);

var_dump($ret);