Can the code snippet provided for checking mandatory keys in an array be directly implemented or does it require modification?
The code snippet provided for checking mandatory keys in an array can be directly implemented. It checks if all mandatory keys are present in the array and returns true if they are, and false if any of them are missing. This can be useful for ensuring that required data is present before proceeding with further processing.
function checkMandatoryKeys($array, $mandatoryKeys) {
foreach ($mandatoryKeys as $key) {
if (!array_key_exists($key, $array)) {
return false;
}
}
return true;
}
// Example usage
$array = ['name' => 'John', 'age' => 30, 'email' => 'john@example.com'];
$mandatoryKeys = ['name', 'email'];
if (checkMandatoryKeys($array, $mandatoryKeys)) {
echo "All mandatory keys are present in the array.";
} else {
echo "Some mandatory keys are missing from the array.";
}