PHP array function that returns a subset for given keys

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

You can use array_intersect_key, but it uses second array with keys and values. It computes the intersection of arrays using keys for comparison

array_intersect_key

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);
$array3 = array('green' => '', 'blue' => '', 'yellow' => '', 'cyan' => '');
$array4 = array('green', 'blue', 'yellow', 'cyan');

var_dump(array_intersect_key($array1, $array2));
var_dump(array_intersect_key($array1, $array3));
var_dump(array_intersect_key($array1, $array4));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

array(0) {
}