Reputation: 69
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')
Upvotes: 0
Views: 73
Reputation: 144
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);
Upvotes: 0
Reputation: 772
Yes you can use the intersect
built-in function:
$input = array('red', 'green', 'yellow', 'blue');
$whitelist = array('green', 'blue');
$filteredInput = array_intersect($input, $whitelist);
Upvotes: 3