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条回答
等我变得足够好
2楼-- · 2020-02-11 07:45

Use simple way with array_diff and array_keys

$check_array = array('key1', 'key2', 'key3');
if (!array_diff($check_array, array_keys($_POST)))
    echo 'all exists';
查看更多
女痞
3楼-- · 2020-02-11 07:49

Use Array to collect data from form as follow:

  • PersonArray['name],
  • PersonArray['address],
  • PersonArray['email], etc.

and process your form on post as below:

if(isset($_POST['name'])){
      ... 
}
查看更多
在下西门庆
4楼-- · 2020-02-11 07:52

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

查看更多
登录 后发表回答