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

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?

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';

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

Do you need the condition to be met if any of them are set or all?
foreach ($_POST as $var){
if (isset($var)) {
}
}

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

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

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');

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'])){
...
}

Old post but always useful
foreach ($_POST as $key => $val){
$$key = isset($_POST[$key]) ? $_POST[$key] : '';
}

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.

if isset(($_POST['name']) && ($_POST['number']) && ($_POST['address']))
You can also use this. it might be more easy.

Related

Shortcut for checking if all $_POST fields are filled in php

I know that I can check if the superglobal $_POST is empty or not by using
empty / isset
However, I have many fields here. Is there any shortcut to check if all fields are filled? Instead of doing
if (!empty($_POST['a']) || !empty($_POST['b']) || !empty($_POST['c']) || !empty($_POST['d']).... ad nauseum)
Thanks in advance!
You can use array_filter and compare both counts
if(count(array_filter($_POST))!=count($_POST)){
echo "Something is empty";
}
You can loop through the $_POST variable.
For example:
$messages=array();
foreach($_POST as $key => $value){
if(empty($value))
$messages[] = "Hey you forgot to fill this field: $key";
}
print_r($messages);
Here's a function I just authored that might help.
if any of the arguments you pass is empty, it returns false. if not it'll return true.
function multi_empty() {
foreach(func_get_args() as $value) {
if (!isset($value) || empty($value)) return false;
}
return true;
}
Example
multi_empty("hello","world",1234); //Returns true
multi_empty("hello","world",'',1234); //Returns false
multi_empty("hello","world",1234,$notset,"test","any amount of arguments"); //Returns false
You can use a foreach() loop to check each $_POST value:
foreach ($_POST as $val) {
if(empty($val)) echo 'You have not filled up all the inputs';
}

How can I get $_GET values to a variable

In my page, there are multiple $_GET values. ie
if(isset($_GET["projects"]))
{ ..... }
else if(isset($_GET["research"]))
{ ...... }
else if(isset($_GET["publication"]))
{ ..... }
...upto 10 elseif's
Can I shorten this?
Can I get these values {projects,research, publication,..} in a variable.?
Ok so I guess I figured out what you want from your comments. Lets see.
$types = array('projects', 'research', 'publication'); // add as many as you want
$valid = array_intersect_key($_GET, array_flip($types));
if (count($valid) > 1)
die "More than one category is set, this is invalid.";
if (!$valid)
die "No category was set, you must choose one.";
foreach ($valid as $type => $value) // just to split this one element array key/value into distinct variables
{
$value = mysql_real_escape_string($value); // assuming you are using mysql_*
$sql = "SELECT * FROM table WHERE $type = '$value'";
}
...
Yes, you can assign these in a variable -
if(isset($_GET["projects"]))
{
$value = $_GET['projects'];
}
else if(isset($_GET["research"]))
{
$value = $_GET['research'];
}
else if(isset($_GET["publication"]))
{
$value = $_GET['publication'];
}
echo $value;
I'm guessing you're expecting a single value in $_GET, like ?projects=foo or ?research=bar. In that case:
$type = key($_GET);
$value = $_GET[$type];
echo "$type = $value";
$projects = $_GET["projects"];
Or just use directly from $_GET, this is an associative array with all the values.
foreach ($_GET as $key => $value){
if(!empty($value)){
$type = $key; //if you expect a single item
$type[] = $key; //if you expect multiple items
}
}
if the intent is to check if values on a form have been answered/filled out you could use
if(isset($_GET['project'] || ... || isset($_GET['publication'])
{
// Insert Code Here
}
else
{
// Insert Code Here
}
The above code is assuming the fields are not text fields or textareas if those are the types of inputs then instead of
if(isset($_GET['project']))
use
if($_GET['project'] != "")
I didn't completely understood what you are saying but looks like that you are trying to execute something when all $_GET is true. If so then use the code below
if(isset($_GET["projects"]) && isset($_GET["research"]) && isset($_GET["publication"]) )
{ ..... }
Hope this helps you

How to generate a longer isset() statement in PHP?

I have an interesting question today. Lets say I have an array of form fields:
array('field1', 'field2', 'field3');
I would basically want to generate an if statement which check if all of the provided fields are exists or not.
So something like this:
function ($array){
$stm = '';
foreach($array as $key){
$stm .= 'isset($_POST['.$key.']) && ';
}
if (rtrim($stm, ' && ')){
echo 'Fields are exists.';
}
}
The problem with the above function is that it takes the created statement as a String and not a variable, so it always exsits. Is there any way that I can generate something like this, which would work?
You're thinking about this the wrong way. If I understood correctly, you have an array of values, that are also POST keys, and you want to check if all of them are set. In this case I'd do something like:
function isset_multiple($array){
foreach($array as $post_key){
if(!isset($_POST[$post_key])) // if one of them is not set, return false
return false;
}
return true; // none of the foreach loops returned false, so all must be set
}
What you can do is check if array keys are set by using variable names, for example
$keyName = "field1";
if ( isset($_POST[$keyName]) === true ) { /* ... */ }
The example above can be implemented in a foreach loop.
Just execute the isset and count:
function ($array){
$count = 0;
foreach($array as $key){
if (isset($_POST[$key]) $count++;
else // you can already exit here...
}
if (count($array) === $count){
echo 'All fields exist.';
}
}
Try this..
function arrayHasKeys(array $array, array $keys)
{
return !((bool) array_diff_key($array, $keys));
}
var_dump(arrayHasKeys($_POST, array('field1', 'field2', 'field3')));
Its quite simple and reusable. Its not a good practice to use global vars inside a function.

Form processing $_POST to variables automatically

I have about 40 items in my FORM and i'm trying to give all the Name= properties a variable for process without having to write each out manually. am I missing something here, cause the code below is not working. (name="comp1", name="comp2"... $comp1, $comp2)
$en = array_merge($em, $_POST);
$valid = true;
foreach($_POST as $value) {
if(!isset($value)) {
$valid = false;
}
}
If something is not in $_POST, the foreach will not loop through it. Isset() will always return true, because the foreach loops through all values in $_POST.
foreach($_POST as $k=>$val) {
//$$k = $val;
if(!isset($$k)){
echo "==NO==";
}
}
the POST will always be set, unless you disable the field with something like this:
<input disabled="disabled"/>
If the filds doesn't have this attribute, the only way to check if the field was filled is a comparse with an empty string, with $value == '' this way:
foreach($_POST as $key => $value) {
if($value == '') {
$valid[$key] = false;
}else{
$valid[$key] = true;
}
}
You will have now an array ($valid) that will look like:
var_dump($valid['field1']); //prints true, the field was filled
var_dump($valid['field2']); //prints false, the field was NOT filled

Access PHP array element with a function?

I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so:
$arr[key($arr)]['item']
However, I'd much prefer to use something like:
current($arr)['item'] // invalid syntax
I'm hoping there's a function out there that I've missed in my scan of the documentation that would enable me to access the element like so:
getvalue(current($arr), 'item')
or
current($arr)->getvalue('item')
Any suggestions?
I very much doubt there is such a function, but it's trivial to write
function getvalue($array, $key)
{
return $array[$key];
}
Edit: As of PHP 5.4, you can index array elements directly from function expressions, current($arr)['item'].
Have you tried using one of the iterator classes yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.
This function might be a bit lenghty but I use it all the time, specially in scenarious like:
if (array_key_exists('user', $_SESSION) === true)
{
if (array_key_exists('level', $_SESSION['user']) === true)
{
$value = $_SESSION['user']['level'];
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
Turns to this:
Value($_SESSION, array('user', 'level'), 'DEFAULT VALUE IF NOT EXISTS');
Here is the function:
function Value($array, $key = 0, $default = false)
{
if (is_array($array) === true)
{
if (is_array($key) === true)
{
foreach ($key as $value)
{
if (array_key_exists($value, $array) === true)
{
$array = $array[$value];
}
else
{
return $default;
}
}
return $array;
}
else if (array_key_exists($key, $array) === true)
{
return $array[$key];
}
}
return $default;
}
PS: You can also use unidimensional arrays, like this:
Value($_SERVER, 'REQUEST_METHOD', 'DEFAULT VALUE IF NOT EXISTS');
If this does not work, how is your multidimensional array composed? A var_dump() might help.
$subkey = 'B';
$arr = array(
$subkey => array(
'AB' => 'A1',
'AC' => 'A2'
)
);
echo current($arr[$subkey]);
next($arr[$subkey]);
echo current($arr[$subkey]);
I often use
foreach ($arr as $key=>$val) {
$val['item'] /*$val is the value of the array*/
$key /*$key is the key used */
}
instead of
next($arr)/current($arr)

Categories