0

I have a function that receives an array as input. ("$inputArr")

the array has a white list of allowed elements it might contain. (specified an array called "$allowedArr").

I want to filter out any elements in the input array isn't in the white list of $allowedArr.

I need to keep the $allowedArr an array.

I know how do to this using a foreach loop (code bellow) but I was wondering if there is a built in function in PHP that can do this more efficiently. (without a loop) array_diff won't do because it does the opposite of what I'm trying to accomplish - because i'm not looking for what is different between the two array, but what's similar


$result = myFunc(array('red', 'green', 'yellow', 'blue'));

function myFunc(array $inputArr){
    $allowedArr = array('green', 'blue');
    $filteredArr = array();

    foreach ($inputArr as $inputElement){
        if(in_array($inputElement, $allowedArr)){
            array_push($filteredArr, $inputElement);
        }
    }

    return $filteredArr;
}

the result i'm trying to get is in this case is for $result to be:

array ('blue', 'green')

2 Answers 2

3

Yes you can use the intersect built-in function:

$input = array('red', 'green', 'yellow', 'blue');

$whitelist = array('green', 'blue');

$filteredInput = array_intersect($input, $whitelist);
Sign up to request clarification or add additional context in comments.

Comments

0

Looks simple for this type of structure and i think that you can simply use

$allowed = ['blue', 'green'];

$result = array_intersect(['blue','green','yellow','red'], $allowed);

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.