Search code examples
phparrayshigher-order-functionsbuilt-in

PHP array function that returns a subset for given keys


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.


Solution

  • 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);