如何重写这个php filterArray函数以获得更好的性能

I have a filterArray method in a class which I use for filtering out an array based on another:

function filterArray($needle, $heystack, $always = array())
{
    foreach($heystack as $k => $v)
    {
        if( !in_array($v, $needle) && !in_array($v, $always) )
            unset($heystack[$k]);
    }

    return $heystack;
}

Usage:

$chars  = array('l', 'J', 'F');
$keys   = array('d','D','j','l','N','S','w','z','W','F','m','M','n','t','L','o','Y','y','a','A','c','r','e','T');
$keys   = filterArray($chars, $keys, array('z'));

note that $always is an array of items that should always be present and should not be filtered out. The result of key is:

$keys   = array('l', 'J', 'F', 'z');

This is more of a validation process. Is there a better way to write this and optimize it for performace? because it's used in a class where performance is crucial.

Thank you.

you didn't specify if there is a need to maintain key association, if key association is not required you can do the following function.

function filterArray($needle, $heystack, $always = array())
{
    return array_intersect(array_merge($needle, $always), $heystack);
}

This should do the trick.

function filterArray($needle, $heystack, $always = array()) {

    $merged = array_merge($needle, $always);

    return array_intersect($heystack, $merged);
}