2

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.

2
  • in_array is slow, use a linked-list Commented Sep 2, 2013 at 12:48
  • @DevZer0 That's PHP >= 5.3 my code requires 5.2+ Commented Sep 2, 2013 at 13:17

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is the one. It's much faster. Executed in 0.000007 Seconds on my machine while the old version was executed in 0.0001 second
0

This should do the trick.

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

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

    return array_intersect($heystack, $merged);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.