I need to check if $_POST
variables exist using single statement isset.
if (isset$_POST[\'name\'] && isset$_POST[\'number\'] &&am
$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
}
}
}
$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.
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