Reputation: 1671
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;
}
}
Upvotes: 0
Views: 1164
Reputation: 2269
private function hasContent($field) {
if (!empty($_POST[$field])) {
return true;
} else {
return false;
}
}
I think you should do a minor change.you should also check whether the existed array have value or is it empty.
Upvotes: 2
Reputation: 6190
I think you can try something like this
private function isSubmitted($field) {
return isset($_POST[$field]);
}
private function hasContent($field) {
return !empty($_POST[$field]);
}
Upvotes: 2
Reputation: 522024
""
(an empty string) as its content. Therefore, array_key_exists
will return true
.if not empty return false
is 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.Upvotes: 3