how to check multiple $_POST variable for existence using isset()?

前端 未结 9 740
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 05:17

I need to check if $_POST variables exist using single statement isset.

if (isset$_POST[\'name\']  &&  isset$_POST[\'number\']  &&am         


        
相关标签:
9条回答
  • 2020-12-18 06:11
    $variableToCheck = array('key1', 'key2', 'key3');
    
    foreach($_POST AS $key => $value)
    {
       if( in_array($key, $variableToCheck))
      {
         if(isset($_POST[$key])){
         // get value
         }else{
         // set validation error
        }   
      }
    }
    
    0 讨论(0)
  • 2020-12-18 06:12
    $variables = array('name', 'number', 'address');
    
    foreach($variables as $variable_name){
    
       if(isset($_POST[$variable_name])){
          echo 'Variable: '.$variable_name.' is set<br/>';
       }else{
          echo 'Variable: '.$variable_name.' is NOT set<br/>';
       }
    
    }
    

    Or, Iterate through each $_POST key/pair

    foreach($_POST as $key => $value){
    
       if(isset($value)){
          echo 'Variable: '.$key.' is set to '.$value.'<br/>';
       }else{
          echo 'Variable: '.$key.' is NOT set<br/>';
       }
    
    }
    

    The last way is probably your easiest way - if any of your $_POST variables change you don't need to update an array with the new names.

    0 讨论(0)
  • 2020-12-18 06:20

    That you are asking is exactly what is in isset page

    isset($_POST['name']) && isset($_POST['number']) && isset($_POST['address'])
    

    is the same as:

    isset($_POST['name'], $_POST['number'], $_POST['address'])
    

    If you are asking for a better or practical way to assert this considering that you already have all the required keys then you can use something like:

    $requiredKeys = ['name', 'number', 'address'];
    $notInPost = array_filter($requiredKeys, function ($key) {
        return ! isset($_POST[$key]);
    });
    

    Remember, isset does not return the same result as array_key_exists

    0 讨论(0)
提交回复
热议问题