in_array multiple values
Searching the array for multiple values corresponds to the set operations (set difference and intersection), as you will see below.
In your question, you do not specify which type of array search you want, so I am giving you both options.
ALL needles exist
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_all(["bear", "zebra"], $animals); // true, both are animals
echo in_array_all(["bear", "toaster"], $animals); // false, toaster is not an animal
ANY of the needles exist
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_any(["toaster", "tiger"], $animals); // true, tiger is an amimal
echo in_array_any(["toaster", "brush"], $animals); // false, no animals here
Important consideration
If the set of needles you are searching for is small and known upfront, your code might be clearer if you just use the logical chaining of in_array
calls, for example:
$animals = ZooAPI.getAllAnimals();
$all = in_array("tiger", $animals) && in_array("toaster", $animals) && ...
$any = in_array("bear", $animals) || in_array("zebra", $animals) || ...
Intersect the targets with the haystack and make sure the intersection count is equal to the target's count:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack
is a superset of $target
.
To verify that at least one value in $target
is also in $haystack
, you can do this check:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}