only update if value is not empty in foreach statement - php

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

Related

Printing multiple empty variables as "Not Available" with a specific style

I'm trying to print the value of empty variables as "Not available" with a specific style (class = 'not-available'). The data will be taken from multiple custom fields and some of them may have an empty value. I'm already doing this with the following code in PHP. My question: is there any alternative way to do the same more efficiently without checking each variable separately?
$na = "<span class='not-available'>Not available</span>";
$prog_auth_id = get_field('prog_auth_id');
if(empty($prog_auth_id)) $prog_auth_id = $na;
$prog_entity_cat = get_field('prog_entity_cat');
if(empty($prog_entity_cat)) $prog_entity_cat = $na;
$prog_assoc_entity = get_field('prog_assoc_entity');
if(empty($prog_assoc_entity)) $prog_assoc_entity = $na;
You can use variable variables in a loop to identify the variables that are empty or not and style them as desired:
$fields = ['prog_auth_id', 'prog_entity_cat', 'prog_assoc_entity'];
foreach($fields as $value) {
$$value = (empty($$value)) ? $na : $$value;
}
working demo

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 = "";
}

How can I shorten my code with isset values

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

undefined variable and undefined index php errors

I've been given the task to remove undefined variable and undefined index errors, which i know how to
$value = isset($_POST['value']) ? $_POST['value'] : '';
The problem is this is way too time consuming, I predict over 2000 variables, $_GET, $_POST hasn't been set. So is there a regular expression i can use to set these variables quickly?
How do i do regex to change this $category = $_GET['c'] to this
$category = isset($_GET['c']) ? $_GET['c'] : ''?
And how do i do regex to change if($page or $category or $profile) to this
if(isset($page) or isset($category) or isset($profile))?
This is the best method i can think of by using regex find & replace in Notepad++. I assume over 2000 PHP variable/index undefined errors. How do i solve this without turning off errors?
you should not use regex because it's kind of heavy :)
if i'm understanding your question right, you can do this like this,
with this approach, it does not matter how many parameters contains POST or GET, you simply filter them through foreach loop and getting clean arrays with parameters, also you can make it a function that returning array.and then you just need to check if_array_key_exests() and do your things.
$_POST = ["user"=>"1", "num"=>2];
$_GET = ["user" => '', "num"=>1];
//function method
function filter($array)
{
$arr = array();
foreach ($array as $key => $val) {
if (!empty($val)) {
$arr[$key] = $val;
}
}
return $arr;
}
without function
$post = array();
foreach ($_POST as $key => $val) {
if (!empty($val)) {
$post[$key] = $val;
}
}
$get = array();
foreach ($_GET as $key => $val) {
if (!empty($val)) {
$get[$key] = $val;
}
}
For your first problem, replacing something like
(\$\w+)\s*=\s*\$_GET\[['"]?(\w+)['"]?\]\s*;
by
$1 = isset($_GET['$2']) ? $_GET['$2'] : '';
should work.
Regarding the second, I don't know if this is possible with a variable number of variables. This one works for 3 variables, replace
if\s*\(\s*\s*(\$\w+)\s+or\s+(\$\w+)\s+or\s+(\$\w+)\s*\)
by
if (isset($1) or isset($2) or isset($3))
You can add another \s+or\s+(\$\w+) before the last \s* in the search, and add another or isset($4) in the replacement for 4 variables etc.
I recommend you to replace them one by one instead of replacing all at once ;-)
Also note that if ($a) is not the same as if (isset($a)). Consider something like this:
// query string is a=0
$a = $_GET['a'];
if ($a) // will be false
if (isset($a)) // will be true
if (!empty($a)) // will be false
So, perhaps you want to use !empty() instead of isset(). This should work without notices, too.
resove first issue:
define a function like:
function global_get($key){
return isset($_GET[$key])?$_GET[$key]:'';
}
then use sed(linux tool) to replace all parts like this(it will modify all the $_GET[.*] of php extension files in your project,so be careful to use this):
find /yourproject -name "*.php" -exec sed -i "s/\$_GET\[\([^]]*\)\]/global_get(\1)/" \;
you may modify this command to apply your own demand.
The second issue could be harmful if you use the regex expression because it is hard to make a role rule.so I recommend you to replace manually.

Cycle through $_POST variables and modify undefined with PHP

I want to look through my PHP $_POST variables and change anything that is "undefined" (because of how jQuery is sending it) to "" or at least " " so that when the email form is submitted it doesn't say "undefined" wherever the value wasn't filled out (optional fields).
Thanks!
I recommend you consider altering your javascript to handle the undefines better, BUT..
Here is a no loops approach to do it:
$_POST = unserialize(str_replace('s:9:"undefined";', 's:0:"";', serialize($_POST)));
There is also the more typical approach of using a single loop like so:
foreach($_POST as &$p) if($p=='undefined') $p = '';
Note: The serialize + unserialize approach is cool in that is does not use a loop, but the loop approach is probably slightly faster, especially when $_POST is large.
In PHP if you use an & symbol in an foreach loop it will use it as a reference instead of a value. Changing a reference will set the original value.
<?php
$_POST['text1'] = 'undefined';
$_POST['text2'] = 'undefined';
foreach($_POST as &$var)
{
if($var == 'undefined')
$var = '';
}
print_r($_POST);
?>
<!-- Will output -->
array(
text1=>
text2=>
)
if (isset($_POST['var'])) {
// it is set
} else {
// it isnt set
}
foreach ($_POST as &$var) {
if ($var === 'undefined') {
$var = '';
}
}

Categories