how to check multiple $_POST variable for existenc

2020-02-11 07:05发布

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

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

is there any easy way to achieve this?

9条回答
We Are One
2楼-- · 2020-02-11 07:25
$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.

查看更多
乱世女痞
3楼-- · 2020-02-11 07:31
$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
    }   
  }
}
查看更多
Melony?
4楼-- · 2020-02-11 07:35

Do you need the condition to be met if any of them are set or all?

foreach ($_POST as $var){
    if (isset($var)) {

    }
}
查看更多
做自己的国王
5楼-- · 2020-02-11 07:41

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

You can also use this. it might be more easy.

查看更多
太酷不给撩
6楼-- · 2020-02-11 07:43

The following is a custom function that take an array for the required posted elements as a parameter and return true if they all posted and there is no any of them is empty string '' or false if there is at least one of them is not:

function checkPosts($posts){
  if (!is_array($posts)) return "Error: Invalid argument, it should be an array";
  foreach ($posts as $post){
    if (!isset($_POST[$post]) || $_POST[$post] == '') return false;
  }
  return true;
} 
// The structure of the argument array may be something like:

$myPosts = array('username', 'password', 'address', 'salary');
查看更多
不美不萌又怎样
7楼-- · 2020-02-11 07:44

Old post but always useful

foreach ($_POST as $key => $val){
$$key = isset($_POST[$key]) ? $_POST[$key] : '';
}
查看更多
登录 后发表回答