haunted85
haunted85

Reputation: 1671

Can't check if $_POST variable has left empty

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

Answers (3)

Rohit Choudhary
Rohit Choudhary

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

Prasad Rajapaksha
Prasad Rajapaksha

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

deceze
deceze

Reputation: 522024

  1. Even when a field is left empty, it is submitted with "" (an empty string) as its content. Therefore, array_key_exists will return true.
  2. if not empty return false is the opposite logic of what you're trying to do.
  3. Abbreviating your boolean returns to return array_key_exists($field, $_POST); should be considered saner, at the very least more concise.

Upvotes: 3

Related Questions