Skip to content
Advertisement

removing elements from an array – that DON’T appear in another array in PHP

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

Advertisement

Answer

Yes you can use the intersect built-in function:

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

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

$filteredInput = array_intersect($input, $whitelist);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement