The other answers work with the given use case, however, you might get a false positive if you're checking "[]
exists in $all
". One way you can account for this edge case using array_diff()
is like so:
function hasAllElems(array $arr1, array $arr2): bool
{
if (empty($arr1) && ! empty($arr2)) {
return false;
}
return ! array_diff($arr1, $arr2);
}
$searchThis = [0 => 200, 1 => 234];
$all = [0 => 307, 1 => 157, 2 => 234, 3 => 200, 4 => 322, 5 => 324];
var_dump(hasAllElems($searchThis, $all)); // true
var_dump(hasAllElems($all, $searchThis)); // false
var_dump(hasAllElems([], $all)); // false
var_dump(hasAllElems($searchThis, [])); // false
Here, by making an explicit check (i.e. if first array is empty and the second array is not empty), you can return false
early in the code.
You can, of course, also use array_intersect()
or a loop to achieve the same.
Wrote a blog post for those interested in learning more.