Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 949
PHP Avatar asked Jun 19 '13 08:06

PHP


People also ask

What is if isset ($_ POST?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What is if isset ($_ POST submit )) in PHP?

Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.

Why isset () is required explain with example when we need to use Isset?

The isset() function is a built-in function of PHP, which is used to determine that a variable is set or not. If a variable is considered set, means the variable is declared and has a different value from the NULL. In short, it checks that the variable is declared and not null.

How do I use isset?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.


3 Answers

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';
like image 55
sectus Avatar answered Sep 18 '22 11:09

sectus


$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.

like image 32
ajtrichards Avatar answered Sep 21 '22 11:09

ajtrichards


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

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

    }
}
like image 43
Vigintas Labakojis Avatar answered Sep 22 '22 11:09

Vigintas Labakojis