I am working with a set of variables that i check each time a page loads. I have successfully checked through $_REQUEST and $_SESSION, but am having trouble with the dynamci checking of variables assigned higher int he page, if they were set.
the following is my code:
$important_field = array('treatmentId','category','state','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (!$$key || $$key == "none" || $$key == "" || $$key == NULL) {
if (!$_REQUEST[$key] || $_REQUEST[$key] == "" || $_REQUEST[$key] == NULL) {
if (!$_SESSION[$key]) {
// wow, guess it just wasn't set anywhere...
} else {
$user->sell->$key = $_SESSION[$key];
}
} else {
$user->sell->$key = $_REQUEST[$key]; $_SESSION[$key] = $_REQUEST[$key];
}
} else {
$user->sell->$$key = $$key; $_SESSION[$$key] = $$key;
}
}
Apparently evaluating $$key does not seem to do what i'm looking for as it never assigns the variable to the session... how should I be evaluating the $key to get the currently set value of say, field $eobFileLocation if it was already set in the PHP prior to the check?
Thanks,
Silver Tiger
Update:
ok, i have the following code, but there's still one bug with it. When i follow my process through af ew of these variables are set on each page and are carried over by the session variable as expected. The issue I am still having is that when i submit a new $_REQUEST variable which SHOULD change the session variable to the new submitted value, the script is finding a local variable ... where is it pulling $key and $$key from that is finding these as a local variable?
$important_field = array('treatmentId','category','state','city','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (isset($$key) && !empty($$key) && $$key != "none") {
echo "Found local variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $$key;
$_SESSION[$key] = $$key;
} elseif (isset($_REQUEST[$key]) && !empty($_REQUEST[$key])) {
echo "Found submitted form variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $_REQUEST[$key];
$_SESSION[$key] = $_REQUEST[$key];
} elseif (isset($_SESSION[$key]) && !empty($_SESSION[$key])) {
echo "Found a session variable ".$key.", i'll set the user to this.<br>\n";
$user->sell->$key = $_SESSION[$key];
} else {
echo "There was no provided data for ".$key."<br>\n";
}
}
Any ideas why when i load the page it thinks the local (as listed above) is set? does $key and $$key read from $_SESSION['blah']/$_REQUEST['blah'] and think it's just $blah?
Are you sure this is what you want:
$user->sell->$$key = $$key;
should it not be
$user->sell->$key = $$key;
try using the empty function:
if (empty($$key) || $$key == "none")
if (empty($_REQUEST[$key]))
and the isset function:
if (!isset($_SESSION[$key]))
it is
$user->sell->$key = $$key;
not
$user->sell->$$key = $$key;
and
$_SESSION[$$key]
should be
$_SESSION[$key]
You're messing with your variables, this is not good. In fact, using two var signs ($$) describes a "variable variable".
$foo = "name";
$$foo = "value";
So you expect the following:
echo $foo; // => "name"
echo $$foo; // => "value"
What you maybe are not expecting, is:
echo $name; // => "value"
So you're better off cleaning up your code first.
Well, I have expressed my concerns about the cleanliness of this approach in the comments. Here's at least some more compact code without variable variables to do the same thing:
$keys = array('treatmentId', 'category', ...)
$values = array_filter(array_merge(
array_intersect_key($_SESSION, array_flip($keys)),
array_intersect_key($_REQUEST, array_flip($keys)),
compact($keys)
), function ($v) { return $v && $v != 'none'; });
$_SESSION = array_merge($_SESSION, $values);
foreach ($values as $key => $value) {
$user->sell->$key = $value;
}
// For debugging purposes:
//
// $diff = array_diff_key(array_flip($keys), $values);
// if ($diff) {
// 'No values for ' . join(', ', array_keys($diff));
// }
Related
i have a variable array that gets all what my function has retrieved.
$array = $funcs->searchCompany($bizName);
and then i used foreach to check if the value is null for varchar and 0 for int and then i replace its value to "Not Provided" so that everytime it is being called it will say "Not Provided"
foreach ($array as $var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $var['name'];
$url = $var['url'];
$tagline = $var['tagline'];
$descrip = $var['descrip'];
$bemail = $var['bemail'];
$address = $var['address'];
$city = $var['city'];
but it seems wrong because it destroys the output instead.
You can use & here to pass the value of array to change inside foreach without actually worrying about which is the current array key, which is also sometimes called as passing a variable's value by reference.
Using foreach
foreach ($array as &$value) // note the &
{
if(empty($value)) $value = 'Not Provided';
// other values remain untouched
}
Using array_map()
$array = array_map(function($value){
if(empty($value))
return 'Not Provided';
return $value;
}, $array);
But i will suggest to go with foreach.
update your function so something like
foreach ($array as &$var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $array['name'];
$url = $array['url'];
$tagline = $array['tagline'];
$descrip = $array['descrip'];
$bemail = $array['bemail'];
$address = $array['address'];
$city = $array['city'];
I would try something like this . I can not write comments so I am writing it as an answer.
What I understand from your code is your array has key value relation. That is most probably why it is not working with your single dimensional array iteration.
try this instead.
foreach ($array as $var => $value) {
if($value == " " || $value == 0 || $value == null) {
$array[$var] = "Not Provided";
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
Give it a try.
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
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.
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
I have a form that passes something like in a URL
?choice=selection+A&choice=selection+C
I'm collecting it in a form with something like (I remember that $_GET is any array)
$temp = $_GET["choice"];
print_r($temp);
I'm only getting the last instance "selection C". What am I missing
I am assuming 'choice' is some kind of multi-select or checkbox group? If so, change its name in your html to 'choice[]'. $_GET['choice'] will then be an array of the selections the user made.
If you don't intend to edit the HTML, this will allow you to do what you're looking to do; it will populate the $_REQUEST superglobal and overwrite its contents.
This assumes PHP Version 5.3, because it uses the Ternary Shortcut Operator. This can be removed.
$rawget = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : false;
$rawpost = file_get_contents('php://input') ?: false;
$target = $rawget;
$_REQUEST = array();
if ($target !== false) {
$pairs = explode('&',$rawget);
foreach($pairs as $pair) {
$p = strpos($pair,'=');
if ($p === false && !empty($pair)) {
$_REQUEST[$pair] = null;
}
elseif ($p === 0 || empty($pair)) {
continue;
}
else {
list($name, $value) = explode('=',$pair,2);
$name = preg_replace('/\[.*\]/','',urldecode($name));
$value = urldecode($value);
if (array_key_exists($name, $_REQUEST)) {
if (is_array($_REQUEST[$name])) {
$_REQUEST[$name][] = $value;
}
else {
$_REQUEST[$name] = array($_REQUEST[$name], $value);
}
}
else {
$_REQUEST[$name] = $value;
}
}
}
}
As it stands, this will only process the QueryString/GET variables; to process post as well, change the 3rd line to something like
$target = ($rawget ?: '') . '&' . ($rawpost ?: '');
All that having been said, I'd still recommend changing the HTML, but if that's not an option for whatever reason, then this should do it.