How can I shorten my code with isset values - php

Im am so lost. Can anyone explain how i can shorten this code. I have hundreds of these! I submit a form with input value. Whenever i dont fill in a value, i get an error. So i made these isset blocks to prevent returning the error. But i seem so unefficient! Please help...thanks
if(isset($_POST['input74'])){
$value74 = $_POST['input74'];
}else{
$value74 = "";#default value
}
if(isset($_POST['input75'])){
$value75 = $_POST['input75'];
}else{
$value75 = "";#default value
}
if(isset($_POST['input76'])){
$value76 = $_POST['input76'];
}else{
$value76 = "";#default value

you could wrap the isset in a function like this
function myIsset(&$variable, $default = "")
{
if(isset($variable))
{
return $variable;
}
else
{
return $default;
}
}
then you just call it like $value74 = myIsset($_POST['input74']);
the second argument defaults to an empty string so if you want to set the default value you can supply it or change what the default is in the function header if they will just all be the same. bellow is a screen shot showing the code working
while yes you are still going to have one line per $_POST at least you exchnge 5 lines of code with 1 line of code and the function above. you can possibly reduce this to a loop like how i explain in this answer however without seeing the form and confirming any pattern i can't give any code examples for that since what you have shown could just be a coincidence

PHP 7 has a new operator to address this specific situation: the null coalesce operator (??) replaces this:
$foo = isset($foo) ? $foo : $bar
With this:
$foo = $foo ?? $bar;

PHP has support for arrays in forms. You can name your form fields with indexes, e.g. <input type="text" name="input[74]" ... />. Then in PHP, you can access those with a for or foreach loop, because they will be available as an array (i.e. you will have $_POST["input"][74]). You could thus write something like:
$values = $_POST["input"];
for ($i = 0; $i < MAX_INPUTS; $i++) {
if (!isset($values[$i])) {
$values[$i] = ""; // default value
}
}
If for some reason you can't change the HTML side, you could still use a loop to dynamically create the field names and copy the data to an array on the PHP side, something like:
$value = array();
for ($i = 0; $i < MAX_INPUTS; $i++) {
$name = sprintf("input%d", $i);
if (isset($_POST[$name])) {
$value[$i] = $_POST[$name];
} else {
$value[$i] = ""; // default
}
}
In both proposed solutions, you only have some lines of code instead of dozens of repetitions of almost the same lines. In both examples, I assumes that your fields start with input0 and that there is a total of MAX_INPUTS fields. If not all fields exist (e.g. you only have input1, intput2, input74 and input75), you can create an array with the fields numbers:
$field_list = array(1,2,74,75);
And then use that to check your data (here the example with arrays in HTML field names):
$values = $_POST["input"];
foreach ($field_list as $num) {
if (!isset($values[$num])) {
$values[$num] = ""; // default value
}
}

Use ternaries to shorten the code:
$value74 = isset($_POST['input74']) ? $_POST['input74'] : 'Default value';
$value75 = isset($_POST['input75']) ? $_POST['input75'] : 'Default value';
$value76 = isset($_POST['input76']) ? $_POST['input76'] : 'Default value';
Or you could loop through $_POST array as well, but some filtering/validation must be done. Quick idea:
if(!empty($_POST)) {
$i = 0;
$arr = array();
foreach($_POST as $input) {
$arr[$i] = $input;
$i++;
}
}
$arr would then produce an array like
Array
(
[74] => 'value74'
[75] => 'value75'
[76] => 'value76'
)

If I understand you correctly seeing that you want to set a variable to post or otherwise default value you can do it following the below structure:
$variable = isset($_POST['name']) ? $_POST['name] : "defaultvalue";
That will set the variable of it exists otherwise set the default value specified. I hope this helps.

You could use array_merge.
You would set up your default array with all the default input values provided.
$aryDefault = ['input74'=>'', 'input75'=>'',...]
Then array_merge this with your post array, and it will fill in all the missing values. NOTE: Order is important check out the docs.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.
Use array_merge($aryDefault, $_POST) so that $_POST overwrites the defaults.
Also, you can use variable variables so you can do this in a loop. If all your variable are named after your array keys, like in your example.
Full Code:
$aryDefault = ['input74'=>'', 'input75'=>'',...];
$aryFinal = array_merge($aryDefaults, $_POST);
foreach( $aryFinal as $key=>$value){
$$key = $value;
}
You could even generate $aryDefault with a loop, if its super big.
$aryDefault = array();
for(i=0;i<=100;i++){
$aryDefault["input$i"] = "";
}

You can create a simple function to encapsulate the code before PHP 7:
function post($key, $default = null){
return isset ($_POST[$key])?$_POST[$key]:$default;
}
Since PHP 7 (using the null coalescing operator (??)):
function post($key, $default = null){
return $_POST[$key] ?? $default;
}
or better whithout function just simple (as mentioned above)
$value74 = $_POST['input74'] ?? ''; #default value
$value75 = $_POST['input75'] ?? ''; #default value
$value76 = $_POST['input76'] ?? ''; #default value

Related

Getting Single Value From Chunked Array

In an array that is chunked into blocks of 11 values, I need to know if a particular one has a TRUE value. If only one is TRUE, that's all I need and the foreach can stop after it sets a value. All I could think of to do was to make it set a SESSION value to TRUE if a match but that does not stop the loop from continuing and then I had the issue of the SESSION giving false results unless it was then unset which I did after the value was set. Seems rather an indirect way to do it so any suggestions?
$FormValues = array_chunk($Fields, $NoValues); // Group together the field values
// Check if form uses multiple selection fields and add appropriate form tags
foreach ($FormValues as $multi) :
if (isset($multi[9]) === TRUE) $_SESSION['useMulti'] = TRUE;
endforeach;
$enableMulti = (isset($_SESSION['useMulti'])) ? " enctype=\"multipart/form-data\"" : "";
unset($_SESSION['useMulti']);
Here is an example of an array and, in this case, none should return TRUE:
$Fields = array("First Name","Title",$Title,1,0,30,"","","","","",
"Quote","Quote",$Quote,4,0,30,"","",$quoteSQL,FALSE,$siteDB,
"Location","Location",$Location,1,0,30,"","","","","",
"Date","EventDate",$EventDate,41,0,15,"",TRUE,"","","",
"Time","Time",$Time,39,0,0,"","",$sqlTime,"","",
);
You can simply iterate over the original array in strides of 11, rather than using array_chunk.
To make the loop stop iterating once you've found what you want, use break.
You don't need a session variable for this, they're only for preserving values between different PHP scripts. You don't really even need another variable, you can just set the enableMulti variable in the loop.
$enableMulti = "";
for ($i = 9; i < count($Fields); $i += $NoValues) {
if ($Fields[$i] === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
If you really want to use foreach you do need to use array_chunk, and you can also use array_column.
$enableMulti = "";
$chunks = array_chunk($Fields, $NoValues);
foreach (array_column($chunks, 9) as $value) {
if ($value === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
You can also get rid of the loop entirely:
if array_search(TRUE, array_column($chunks, 9)) {
$enableMulti = " enctype=\"multipart/form-data\"";
} else {
$enableMulti = "";
}

Easiest way to check if multiple POST parameters are set?

Hi so I want to know the easiest way to check if multiple POST parameters are set. Instead of doing a long if check with multiple "isset($_POST['example'])" linked together by "&&", I wanted to know if there was a cleaner way of doing it.
What I ended up doing was making an array and looping over it:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
I would then call the function below, passing in $params_needed to check if the parameter names above are set:
function all_params_valid($params_needed) {
foreach ($params_needed as $param) {
if (!isset($_POST[$param])) {
error("Missing the " . $param . " variable in POST request.");
return false;
}
}
return true;
}
if (all_params_valid($params_needed)) {
$song_name = $_POST["song_name"];
$artist_name = $_POST["artist_name"];
$song_release_date = $_POST["song_release_date"];
$song_genre = $_POST["song_genre"];
$song_medium = $_POST["song_medium"];
...
}
However when I do this, it gets stuck on the first index and says "Missing the song_name variable..." despite actually including it in the POST request, and I'm not sure why this is happening. The expected behavior would be for it to move on and tell me the next parameter "artist_name" is not set, but this doesn't happen.
I personally like using array_diff for this issue.
PHP array_diff documentation
What you care about is your expected input is the same as the given input.
So you can use array_diff like this:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
$given_params = array_keys($_POST);
$missing_params = array_diff($params_needed, $given_params);
if(!empty($missing_params)) {
// uh oh, someone didn't complete the form completely...
}
How I approach this is by using array_map() so I can return all the values in the array whilst checking if it isset()
PHP 5.6 >
$args = array_map(function($key) {
return isset($_POST[$key]) ? array($key => $_POST[$key]) : someErrorMethod($key);
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
PHP 7+
$args = array_map(function($key) {
return array($key => $_POST[$key] ?? someErrorMethod($key));
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
Your error method could look something like this:
function someErrorMethod($key) { die("$key cannot be empty."); }
Inside of your $args variable, you will have an array of key => value. For example,
echo $args['song_name'];

only update if value is not empty in foreach statement

I keep getting an error Undefined property: stdClass::$ on any $li that is empty, is there a quicker way of not inserting the blank columns / fields? other than if ($li->company != "") I still want it to insert the non empty ones.
foreach ($data as $li) {
$insert['company']= $li->company;
$insert['first']= $li->first;
$insert['last']= $li->last;
$insert['email']= $li->email;
$insert['phone1']= $li->phone1;
$insert['phone2']= $li->phone2;
$insert['phone3']= $li->phone3;
$insert['address1']= $li->address1;
$insert['address2']= $li->address2;
$insert['address3']= $li->address3;
$insert['postcode']= $li->zip;
$insert['city']= $li->city;
$insert['country']= $li->country;
$insert['stage']= $li->stage;
$insert['source']= $li->source;
$insert['website']= $li->website;
$insert['user_ID']= is_user_logged_in();
$insert['owner']= is_user_logged_in();
$insert['assigneduser']= is_user_logged_in();
$insert['stage']= "Prospect";
$this->db->insert("leads", $insert);
}
Use isset() to test if the property is set, and use a default value if it isn't.
$insert['company'] = isset($li->company) ? $li->company : "";
To avoid lots of repetition, you can use a loop:
foreach (['company', 'first', 'last', ...] as $field) {
$insert[$field] = isset($li->{$field}) ? $li->{$field} : "";
}
DEMO
In your Class constructor you can set a default value for all the attributes.
If you cannot modify the constructor, an alternative to have a better readable code is use the ternary operators, an one line if and else variation
For example:
$insert['company'] = (isset($li->company))? $li->company : "";
is the same as
if(isset($li->company))
$insert['company'] = $li->company;
else
$insert['company'] = "";
Wrap it in a test for empty:
if($li->zip) {
$insert['postcode'] = $li->zip;
}

how to store isset condition php to avoid repetition

my code:
if (isset($dayMarks[$res['resId']][$dDate])) {
$var=$dayMarks[$res['resId']][$dDate];
echo $var;
}
note that the isset condition is identical to the value assigned to $var, which creates a pretty ugly code.
How is it possible to assign the condition to $var without repeating it?
(in javascript, I'd write if (var=$dayMarks[$re...) )
This is a common problem in PHP where including files can create uncertainty about variables.
There are a two approaches that work well for me.
Default Assignment
With default assignment the $var variable will be given a default value when the key doesn't exist.
$var = isset($dayMarks[$res['resId']][$dDate]) ? $dayMarks[$res['resId']][$dDate] : false;
After this code can assume that $var will always contain a valid value.
Default Merger
My preferred method is to always declare a default array that contains all the required values, and their defaults. Using the False value to mark any keys that might be missing a value (assuming that key holds another value type besides boolean).
$default = array(
'date'=>false,
'name'=>'John Doe'
);
$dayMarks[$res['resId']] = array_merge($default, $dayMarks[$res['resId']]);
This will ensure that the required keys for that variable exist, and hold at least a default value.
You can now test if the date exists.
if($dayMarks[$res['resId']]['date'] !== false)
{
// has a date value
}
While this might not work exactly for your array. Since it looks like it's a table structure. There is a benefit to switching to named key/value pairs. As this allows you to easily assign default values to that array.
EDIT:
The actual question was if it was possible to reproduce the JavaScript code.
if (var=$dayMarks[$re...)
Yes, this can be done by using a helper function.
NOTE: This trick should only be used on non-boolean types.
function _isset($arr,$key)
{
return isset($arr[$key]) ? $arr[$key] : false;
}
$a = array('zzzz'=>'hello');
if(($b = _isset($a,'test')) !== false)
{
echo $b;
}
if(($c = _isset($a,'zzzz')) !== false)
{
echo $c;
}
See above code here
$isset = isset(...); //save the value
if ($isset) { .... }; // reuse the value
...
if ($isset) { ... }; // reuse it yet again
The only thing you can do is store $res['resId'][$dDate].
$var = $res['resId'][$dDate];
if( isset($dayMarks[$var]) ) {
$var = $dayMarks[$var];
echo $var;
}
If you only want to assign a variable processing simply, you can also write this as:
$var = $dayMarks[$res['resId']][$dDate]);
if (!isset($var)) unset($var);

Function to set default value of associative array if the key is not present

Is there a function in PHP to set default value of a variable if it is not set ?
Some inbuilt function to replace something like:
$myFruit = isset($_REQUEST['myfruit']) ? $_REQUEST['myfruit'] : "apple" ;
PHP kind of has an operator for this (since 5.3 I think) which would compress your example to:
$myFruit = $_REQUEST['myfruit'] ?: "apple";
However, I say "kind of" because it only tests if the first operand evaluates to false, and won't suppress notices if it isn't set. So if (as in your example) it might not be set then your original code is best.
The function analogous to dictionary.get is trivial:
function dget($dict, $key, $default) {
return isset($dict[$key]) ? $dict[$key] : $default;
}
For clarity, I'd still use your original code.
Edit: The userland implementation #2 of ifsetor() at http://wiki.php.net/rfc/ifsetor is a bit neater than the above function and works with non-arrays too, but has the same caveat that the default expression will always be evaluated even if it's not used:
function ifsetor(&$variable, $default = null) {
if (isset($variable)) {
$tmp = $variable;
} else {
$tmp = $default;
}
return $tmp;
}
As far as i know there exists nothing like this in PHP.
You may implement something like this yourself like
$myVar = "Using a variable as a default value!";
function myFunction($myArgument=null) {
if($myArgument===null)
$myArgument = $GLOBALS["myVar"];
echo $myArgument;
}
// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
You could also create a class implementing the ArrayAccess, which you pass 2 arrays during construction ($_REQUEST and an array with defaults) and make it choose the default value transparently.
Btw., relying on $_REQUEST is not a wise idea. See the manual on $_REQUEST for further information.
Instead of testing, if a key not exists and then return a default value, you can also fill your array with this values, before accessing it.
$expectedKeys = array('myfruit');
$requestData = array_merge (
array_combine(
$expectedKeys,
array_fill(0, count($expectedKeys), null)),
$_REQUEST);
$postData is now an array with all keys you expect (specified by $expectedKeys), but any entry, that is missing in $_REQUEST is null.
$myFruit = $requestData['myfruit'];
if (is_null($myFruit)) {
// Value not exists
}
But I also recommend to just stay with the ternary operator ?:.
There is a function called ife() in the CakePHP framework, you can find it here http://api13.cakephp.org/view_source/basics.php/, it is the last function!
You can use it like this:
echo ife($variable, $variable, 'default');

Categories