I need to validate a form therefore I am writing a php class that does just that. I need to check if a $_POST variable has been set or not in order to determine whether display an error message. So I have implemented two methods which don’t seem to work as I expect, because even if I leave my form blank, it is processed as if data has been filled in, and I just don’t understand.
private function isSubmitted($field) {
if (!array_key_exists($field, $_POST)) {
return false;
} else {
return true;
}
}
private function hasContent($field) {
if (!empty($_POST[$field])) {
return false;
} else {
return true;
}
}
""(an empty string) as its content. Therefore,array_key_existswill returntrue.if not empty return falseis the opposite logic of what you’re trying to do.return array_key_exists($field, $_POST);should be considered saner, at the very least more concise.