Reputation: 11255
Currently, this is what I do to check if all keys of an array $A are within a subset of another array $B.
$B = array('a', 'b', 'c', 'd');
if(array_keys($A) == array_intersect(array_keys($A), $B))
{
action if true
}
I am wondering if there is a more straight forward way of doing this, something like the in_array()
function.
Usage Example:
Checking the $_POST array to ensure that all keys matches a dynamic form and filter out extra keys if the form is hacked.
Upvotes: 0
Views: 129
Reputation: 3536
Not perhaps that straight forward to read, but this comment in the PHP manual for array_intersect provides a compact way of checking whether an array is a subset of another.
if (array_unique(array_keys($a) + $b) == $b)
{
echo 'valid array keys';
}
Upvotes: 1
Reputation: 522085
if (array_diff_key($A, array_flip($B))) {
// there are keys in $A that are *not* in $B!
}
or possibly:
if (array_diff_key(array_flip($B), $A)) {
// not all of the keys in $B are in $A!
}
Upvotes: 2
Reputation: 174957
No, your way is probably the same way I would have used. If you need to compare against a list, an array is the best solution. Though I would have probably used array_intersect_keys_
instead.
Upvotes: 0