Check all $_POST Variable at once

后端 未结 3 1742
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 16:30

instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like



        
相关标签:
3条回答
  • 2021-01-15 17:02

    You can create an array of required fields and loop through that

    $required_fields = array("name", "address", "phone", "email");
    foreach ($require_fields as $field) {
        if (!strlen($_POST[$field])) {
            echo "$field cannot be empty";
        }
    }
    
    0 讨论(0)
  • 2021-01-15 17:16

    Can't be done like the way you're thinking (as PHP has no way of knowing what values there should be).

    But you could it like this:

    <?php
      $POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist');
    
      foreach($POSTvaluesToCheck as $key) {
        if(!isset($_POST[$key]) {
          echo $key . ' not set correctly!';
        }
      }
    ?>
    
    0 讨论(0)
  • 2021-01-15 17:23

    No because how would your program know which should exist?

    However, if you have a list of fields that are expected, you can easily write a function to check. I called it array_keys_exist because it does the exact same thing as array_key_exists except with multiple keys:

    function array_keys_exist($keys, $array) {
        foreach ($keys as $key) {
            if (!array_key_exists($key, $array)) return false;
        }
        return true;
    }
    
    $expectedFields = array('name', 'email');
    
    $success = array_keys_exist($expectedFields, $_POST);
    
    0 讨论(0)
提交回复
热议问题