Is this the proper use of an array and isset? - php

So I've got this code and part of it is a form, and ALL fields are absolutely required.
I just can't find clear documentation for my needs to validate everything.
would I do something like this?
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$lorem = $_POST['lorem'];
$ipsum = $_POST['ipsum'];
$isSet = array($foo, $bar, $lorem, $ipsum);
if(isset($isSet)) { /* Do the stuff */ }
or is there a better way? I don't really want to do
if(isset($foo) && isset($bar) && isset($lorem)........
because i've got about 12 fields that are required

You can do:
if (isset($foo, $bar, $lorem, $ipsum)) {.....}
Saves you one step.
http://php.net/manual/en/function.isset.php

Remember that isset will return true if you have an empty string. So, technically
isset($_POST['foo'])
would return true if foo is passed in with a blank value:
foo=&bar=&...etc.
Also,
isset(array())
returns true;
If "" is not a valid value for one of those variables, you will want to do the following:
$requiredFields = array('foo', 'bar', 'lorem', 'ipsum');
$allValid = true;
foreach ($requireFields => $fieldName) {
if (isset($_POST[$fieldName]) && $_POST[$fieldName] != "") {
$allValid = $allValid && true;
} else {
$allValid = $allValid && false;
}
}
if ($allValid) {
//...success...
} else {
//...failed...
}
You essentially check that the variable was passed and also that the variable is not set to "".
Hope that helps.

Related

Fill array regardless if there is empty check

So I have the following code:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
if (empty($obj->birthday) || $obj->hire_date) {
$record->fill([
'birthday' => '',
'hire_date' => ''
]);
} else {
$record->fill($arr);
}
} else {
$record->timestamps = false;
}
Where I'm checking if $obj->birthday or $obj->hire_date is empty, and then define them as empty strings, but here is the problem.
I want to be able to call $record->fill($arr) regardless and prepopulate all my fields on the empty check, but for some reason I can't seem to figure out out.
So heres the logic:
Empty hire_date? set as ''.
Empty birthday? set as ''.
Populate the rest of the fields..
Both hire_date and birthday not empty? Populate all fields.
You can try this:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$filllArray = $arr;
if (empty($obj->birthday) {
$record->fill([
'birthday' => ''
]);
unset($filllArray['birthday']);
}
if (empty($obj->hire_date)) {
$record->fill([
'hire_date' => ''
]);
unset($filllArray['hire_date']);
}
$record->fill($filllArray);
} else {
$record->timestamps = false;
}
Update 1: Copy the $arr to $filllArray and update the new array to determine what should be filled or not.
I know you've accepted an answer. This is a slightly different way of achieving the same thing (If I understood the question correctly)
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$fa = [];
empty($obj->birthday) ? $fa['birthday'] = '' : $fa['birthday'] = $obj->birthday;
empty($obj->hire_date) ? $fa['hire_date'] = '' : $fa['hire_date'] = $obj->hire_date;
$merged_arr = array_merge($arr, $fa);
$record->fill($merged_arr);
} else {
$record->timestamps = false;
}

How to check if any variables are set?

checking if all are set
if(
isset($var1) &&
isset($var2) &&
isset($var3)
){}
can be re-written as
if(isset($var1,$var2,$var3)){}
but what's the syntax for if any are set?
if(
isset($var1) ||
isset($var2) ||
isset($var3)
){}
Looks ugly; is there any better way to write this?
You have to pass strings instead of the variables, but for fun:
if(compact('var1', 'var2', 'var3')) {
echo 'one or more is set';
} else {
echo 'none are set';
}
I guess one could write a simple function to use, but there's probably a cleaner way.
function anyset(...$vars){
foreach($vars as $var){
if(isset($var)){
return true;
}
}
return false;
}
if(anyset($var1,$var2,$var3)){}

in specific condition set and store a variable until another specific condition

Hello I'm pretty new in programming. I need to solve this problem in php but the solution in any different language will be great. I tryied to solve it with if statement but if condition is changed the variable is gone. Easy example for better understanding.
// possible conditions ( 'cond1', 'cond2', 'cond3', 'cond4','cond5' )
// conditions can be called randomly
I would like to have somethng like this:
$variable = 'off';
since ( $condition == 'cond2' )
$variable = 'on';
until ( $condition == 'cond4' )
The goal is to switch variable 'on' in the 'cond2' condition and hold it on when the others conditions are changing independently on their order until condition is changed to 'cond4' and variable is switched back to 'off'.
Thanks for any suggestions.
I don't think your current concept is realizable in PHP as you cannot listen to variables, you need to actively get notified. So one scenario with the same solution but a different concept would be
class Condition {
private $value;
private $variable = false;
public function setCondition($new_value) {
$this->value = $new_value;
}
public function getCondition() {
return $this->value;
}
public function isVariableSet() {
return ($this->variable === true); //TRUE if $this->variable is true
//FALSE otherwise
}
}
Now in the method setCondition(...) you can listen and actively set the variable.
public function setCondition($new_value) {
switch ($new_value) {
case 'cond2':
$this->variable = true;
break;
case 'cond4':
$this->variable = false;
break;
}
$this->value = $new_value;
}
With this you can use it like the following
$foo = new Condition();
$foo->setCondition('cond1');
var_dump( $foo->isVariableSet() ); //FALSE
$foo->setCondition('cond2');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond3');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond4');
var_dump( $foo->isVariableSet() ); //FALSE
Or in your case:
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
foreach ($conditions as $i => $condition) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
$results[$condition] = $toggle.' ; ';
}
If you don't create the instance of Condition outside the loop, you gain nothing as you create a new object everytime and no state stays. However, exactly that is required.
You can also do this via array_map() and save the foreach()
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
$results = array();
$setCondGetVariable = function($condition) use($cond) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
return $toggle.' ; ';
};
$results = array_map($setCondGetVariable, $conditions);

Change $mailTo variable based on select input value (array)

I have the following select list:
<form action="mail.php" method="POST">
<select name="foo" id="foo">
<option value="sales">Sales</option>
<option value="salesAssist">Sales Assist</option>
<option value="billing">Billing</option>
<option value="billingAssist">Billing Assist</option>
</select>
</form>
I need to route the $mailTo variable depending on which option they select, Sales and Sales Assist go to sales#email.com, while Billing and Billing Assist go to billing#email.com.
PHP pseudeo code!
<? php
$_POST['foo'] if inArray(sales, salesAssist) foo="sales#email.com";
else if inArray(billing, billingAssist) foo="billing#email.com";
mailTo="foo"
?>
I know there is nothing correct about the above, but you can see what I am trying to do, change a variable's value based on the selected value. I don't want to do this with JavaScript, I would rather learn more PHP here.
Your pseudocode is pretty much right on. Here is an implementation, using in_array():
if (in_array($_POST['foo'], array('sales', 'salesAssit')) {
$foo = 'sales#email.com';
}
elseif (in_array($_POST['foo'], array('billing', 'billingAssit')) {
$foo = 'billing#email.com';
}
Of course, there are other ways to go about this. With only two values to search for, you could also do something like this:
if ($_POST['foo'] == 'sales' || $_POST['foo'] == 'salesAssit') {
$foo = 'sales#email.com';
}
elseif ($_POST['foo'] == 'billing' || $_POST['foo'] == 'billingAssit') {
$foo = 'billing#email.com';
}
Or, just check for the occurrence of the 'billing' or 'sales', using strpos():
if (strpos($_POST['foo'], 'sales') !== false) {
$foo = 'sales#email.com';
}
elseif (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
However, what I like to do in situations like these, where you know it will always be one option or the other, is assign one as the default, and only change it if necessary:
$foo = 'sales#email.com';
if (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
Try :
function startsWith($haystack, $needle) {
return $needle === "" || strpos($haystack, $needle) === 0;
}
if(startsWith($_POST["foo"], "sales") {
$foo = "sales#email.com";
} else if(startsWith($_POST["foo"], "billing") {
$foo = "billing#email.com";
}
Keep it simple, sir by using and array of e-mail values which you then cross check with array_key_exists.
// Set an array of e-mails.
$email_array = array();
$email_array['sales'] = "sales#email.com";
$email_array['salesAssist'] = "sales#email.com";
$email_array['billing'] = "billing#email.com";
$email_array['billingAssist'] = "billing#email.com";
// Do basic checks on 'foo'. If not? It's null.
$foo = isset($_POST['foo']) && !empty($_POST['foo']) ? $_POST['foo'] : null;
// Now check if 'foo' is in the array. If not? It's null.
$mailTo = !empty($foo) && array_key_exists($foo, $email_array) ? $email_array[$foo] : null;
The benefit of doing it this way is it’s clean & simple. You can set any e-mail you want in the array. And you can even set a default—instead of null—if you wish if somehow the script gets returned with none of the options selected.
Or if ternary logic seems confusing & you would rather just act on the data right away, this will work:
// Do basic checks on 'foo'. And check if 'foo' is in the array. If not? It's null.
$mailTo = null;
if ((isset($_POST['foo']) && !empty($_POST['foo'])) && array_key_exists($_POST['foo'], $email_array)) {
$mailTo = $email_array[$foo];
}

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

Categories