What is the best way to check if an array contains unallowed keys ?
$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);
$allowed = array("Apple", "Orange");
Desired output is:
if (!something($array,$allowed)){echo 'Unallowed data';}
Thanks
Use array_diff_key
$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);
$allowed = array("Apple", "Orange");
$allowed = array_flip($allowed);
$res = array_diff_key($array, $allowed);
print_r($res);
echo $allowedTxt = empty($res) ? "Allowed keys only" : "Not allowed keys";
$res
contains unallowed data.
Assumes not allowed key is "Dogs
"
var_dump(array_intersect_key($array, array_flip($allowed)));
You can use array_diff()
to find keys that are not allowed:
$keys = array_keys($array);
$notAllowed = array_diff($keys, $allowed);
var_dump($notAllowed); // "Dogs"
Here is a function that does this:
function something($array, $keys) {
return ! array_diff(array_keys($array), $keys);
}
// Usage...
if ( ! something($array, $allowed)) {
echo 'Unallowed data';
}
If you can use an associative (map) array for your allowed values, then you can perform the search on the allowed keys in O(1). With your current data structure, searching the allowed map, will take O(n) time.
$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);
$allowed = array("Apple" => 0, "Orange" => 1);
$found_not_allowed = 0;
foreach($array as $key => $value)
if(!isset($allowed[$key]))
$found_not_allowed++;
if($found_not_allowed > 0)
echo "Keys were found that are not allowed.";