7

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?

PHP
  • 159
  • 3
  • 3
  • 12
  • 1
    I have 25 variable for instance – PHP Jun 19 '13 at 09:22
  • I just wondered if you can reduce this operation logically, such as check the submit button $_POST['submit']. While, this is all my guess, if you cannot skip this check @ajtrichards 's reply is good. – 蒋艾伦 Jun 19 '13 at 09:36
  • It cant be ensure 25 variable exist by checking $_POST['submit'] only, Because user may submit a form by editing/deleting an input field using Browser web developer tools such as INSPECT in fire fox . – PHP Jun 19 '13 at 11:56
  • What is wrong with sectus ' answer ? – PHP Jun 19 '13 at 11:57
  • I just saw @ajtrichards 's reply first, and it worked. :) – 蒋艾伦 Jun 19 '13 at 14:41

10 Answers10

19

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';
sectus
  • 15,605
  • 5
  • 55
  • 97
  • 2
    Note that the name of the submit button must be included in the array too. – The Codesee May 09 '20 at 18:22
  • Nice approach. You can also use `array_diff_keys`, but would then need `$check_array` as keys, probably involving an `array_flip`, so I don't think that's any better, unless you happen to already have the properties you want to check for keyed in some other array. – Jake Feb 10 '23 at 03:23
7
$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.

ajtrichards
  • 29,723
  • 13
  • 94
  • 101
  • I want to check for Existence of variable , not for NOT NULL. Then is your second option is right ? – PHP Jun 19 '13 at 09:10
  • Go with the first one - put the variables in an array and check if there is a `$_POST` variable that matches – ajtrichards Jun 19 '13 at 09:11
  • Create a function with this code and use the return value (TRUE or FALSE) – PHP Jun 20 '13 at 05:25
2

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

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

    }
}
Arnaud Leyder
  • 6,674
  • 5
  • 31
  • 43
Vigintas Labakojis
  • 1,039
  • 1
  • 15
  • 21
1
$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
    }   
  }
}
Irfan DANISH
  • 8,349
  • 12
  • 42
  • 67
  • This code just check whether the $_POST variable is in the defined array. But doesnt check all variables in the defined array . Hence this code is not useful for the purpose in the question. – PHP Jun 20 '13 at 05:31
  • This code does, first it iterates over all post variables and check if the current variable should be validated or not, if it should validate then there is isset() check as you required in your question. – Irfan DANISH Jun 20 '13 at 09:50
  • you are testing 25 post variable, what if you are sending more variables in your post like 30 (hidden field, post button etc). Then you have to find which 25 to check. – Irfan DANISH Jun 20 '13 at 09:51
1

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

Carlos C Soto
  • 1,025
  • 9
  • 11
0

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');
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
0

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'])){
      ... 
}
ersks
  • 1,409
  • 2
  • 16
  • 23
0

Old post but always useful

foreach ($_POST as $key => $val){
$$key = isset($_POST[$key]) ? $_POST[$key] : '';
}
0

Use simple way with in_array and array_keys

$check_array = array('key1', 'key2', 'key3');

if(in_array(array_keys($_POST), $check_array)) {
    echo 'all exists';
}

Note that the name of the submit button must be included in the array too.

Sandra
  • 1,596
  • 15
  • 22
-3

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

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

  • 2
    This cannot work, `isset()` works only with variables. Your example builds a boolean expression, then tries to test the result (true or false) with isset. The outcome of the boolean expression would depend on the content of the `$_POST` variables. – martinstoeckli Jun 19 '13 at 12:15
  • Even with the missing brackets added, it generates a compile-time error: "Cannot use `isset()` on the result of an expression." Please test your code before posting it as an answer. – Jake Feb 10 '23 at 03:17
  • @Jake this is not spam content, please do not flag incorrect answers as such. – Samuel Liew Feb 10 '23 at 04:07
  • @SamuelLiew Some questions on the site require a certain reputation to answer, because they've received many "spammy" answers (SO's words not mine). None of them are actual spam, just poor quality from people with no knowlege trying to self-aggrandize. So I am lost in terms of knowing what you consider spam. This conversation should not be had here. It is a shame there is no DM faclity. – Jake Feb 12 '23 at 03:45
  • You can start a discussion on [meta], like this: https://meta.stackoverflow.com/questions/284768/answers-flagged-as-spam-moderator-rejects – Samuel Liew Feb 12 '23 at 06:31
  • 1
    @Jake You can start a discussion on [meta], like this: https://meta.stackoverflow.com/questions/284768/answers-flagged-as-spam-moderator-rejects – Samuel Liew Feb 12 '23 at 06:32